/*
 * @(#)DocumentRetrievalManager.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Arg;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Form;
import org.apache.commons.validator.ValidatorResources;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Hits;
import org.apache.struts.validator.ValidatorPlugIn;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.alert.dao.UpdateAlertTypeDAObject;
import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsArchive;
import com.dcivision.dms.bean.DmsArchiveDetail;
import com.dcivision.dms.bean.DmsContent;
import com.dcivision.dms.bean.DmsDefaultProfileSetting;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsDocumentIndex;
import com.dcivision.dms.bean.DmsLocMaster;
import com.dcivision.dms.bean.DmsObjectHomeFolder;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.bean.MtmDocumentRelationship;
import com.dcivision.dms.dao.DmsArchiveDetailDAObject;
import com.dcivision.dms.dao.DmsContentDAObject;
import com.dcivision.dms.dao.DmsDefaultProfileSettingDAObject;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsDocumentDetailDAObject;
import com.dcivision.dms.dao.DmsDocumentIndexDAObject;
import com.dcivision.dms.dao.DmsObjectHomeFolderDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.dms.dao.DmsVersionDAObject;
import com.dcivision.dms.dao.MtmDocumentRelationshipDAObject;
import com.dcivision.dms.dao.MtmDocumentVersionDAObject;
import com.dcivision.dms.web.ListDmsDocumentForm;
import com.dcivision.dms.web.MaintDmsDocumentForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.SysUserDefinedIndex;
import com.dcivision.framework.bean.SysUserDefinedIndexDetail;
import com.dcivision.framework.dao.SysUserDefinedIndexDAObject;
import com.dcivision.framework.dao.SysUserDefinedIndexDetailDAObject;
import com.dcivision.user.bean.UserPermissionInherit;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserPermissionInheritDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;


/**
 * <p>Class Name:       DocumentRetrievalManager.java    </p>
 * <p>Description:      The class mainly handle the dmsDocument list process and retrieval operations.</p>
 * @author              Zoe Shum
 * @company             DCIVision Limited
 * @creation date       01/08/2003
 * @version             $Revision: 1.167.4.5 $
 */ 
public class DocumentRetrievalManager {

  public static final String REVISION = "$Revision: 1.167.4.5 $";

  public static final String FILE_SEPARATOR = File.separator;

  protected Log log = LogFactory.getLog(this.getClass().getName());
  private DmsDocumentNameConvertor documentNameConvertor = null;
  private SessionContainer sessionContainer;
  private Connection conn;

  /**
   *  Constructor - Creates a new instance of DocumentRetrievalManager
   */
  public DocumentRetrievalManager(SessionContainer sessionContainer, Connection conn) {
    this.sessionContainer = sessionContainer;
    this.conn = conn;
  }

  /**
   *  Release - release all variable in instance of DocumentRetrievalManager
   */
  public synchronized void release() {
    this.sessionContainer = null;
    this.conn = null;
    documentNameConvertor = null;
  }

  /**
   * Gets the physical location path corresponding of the dmsDocument.
   * 
   * @param newDmsDocument        dmsDocument for checking location master
   * @return StringBuffer         Location path
   * @throws ApplicationException 
   */

  public synchronized StringBuffer getFoldersDirectories(DmsDocument newDmsDocument) throws ApplicationException {
    StringBuffer targetDirectories = new StringBuffer();

    try {
      this.documentNameConvertor = (DmsDocumentNameConvertor) Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_NAME_CONVERTOR_CLASS)).newInstance();
    } catch (Exception e) {
      log.error("Name Convertor class not found.", e);
      throw new ApplicationException(DmsErrorConstant.NAME_CONVERTOR_CLASS_NOT_FOUND);
    }
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    DmsLocMaster locMaster = rootRetrievalManager.getTargetLocMasterByDocument(newDmsDocument);
    targetDirectories.append(locMaster.getLocPath() + "/");
    log.debug("loc Master = " + locMaster.getLocPath());

    /*check its parent folder name
         DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
         List parentFolders = (List) docRetrievalManager.getAllParentFoldersName(newDmsDocument);
         StringBuffer foldersDir = new StringBuffer();
         if (parentFolders!=null) {
      for (int i=parentFolders.size()-1; i>=0; i--) {
        foldersDir.append((String)parentFolders.get(i)+"/");
      }
         }
         log.debug("folder dir = " + foldersDir);
     */
    rootRetrievalManager.release();
    return targetDirectories;
  }

  /**
   *  Get the all the CONVERTED parent folder's name for target dmsDocument.
   *
   *  @param      documentID               The target dmsDocument ID
   *  @return     List                     The (List) that consists of all the parent folder ordered in position
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized List getAllParentFoldersName(DmsDocument dmsDocument) throws ApplicationException {
    List parentFolders = new ArrayList();
    int i = 0;
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsDocument parentDocument = (DmsDocument) dmsDocumentDAO.getVersionDetailByDocumentID(dmsDocument.getParentID());
    DmsContentDAObject dmsContentDAO = new DmsContentDAObject(sessionContainer, conn);
    DmsContent dmsContent = (DmsContent) dmsContentDAO.getObjectByID(parentDocument.getContentID());
    if (parentDocument.getParentID() != null) {
      String convertedName = dmsContent.getConvertedName();
      parentFolders.add(convertedName);
      while (parentDocument.getParentID().intValue() != 0) {
        parentDocument = (DmsDocument) dmsDocumentDAO.getVersionDetailByDocumentID(parentDocument.getParentID());
        DmsContentDAObject upperDmsContentDAO = new DmsContentDAObject(sessionContainer, conn);
        DmsContent upperDmsContent = (DmsContent) dmsContentDAO.getObjectByID(parentDocument.getContentID());
        String upperConvertedName = upperDmsContent.getConvertedName();
        parentFolders.add(upperConvertedName);
      }
    }
    dmsDocumentDAO = null;
    return parentFolders;
  }

  /**
   *  Get the all document by document ID.
   *
   *  @param      documentID               The target dmsDocument ID
   *  @return     DmsDocument              The (DmsDocument) that met the documentID
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized DmsDocument getDocument(Integer documentID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsDocument dmsDocument = (DmsDocument) dmsDocumentDAO.getObjectByID(documentID);
    dmsDocumentDAO = null;
    return dmsDocument;

  }
  /**
     *  Get the all document by document ID.
     *
     *  @param      documentID               The target dmsDocument ID
     *  @return     DmsDocument              The (DmsDocument) that met the documentID, null if record not found
     *  @throws     ApplicationException     Throws when operation fault
     */
  
  public synchronized DmsDocument getDocumentByID(Integer documentID) throws ApplicationException {
     DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
     DmsDocument dmsDocument = (DmsDocument) dmsDocumentDAO.getDocumentByID(documentID,GlobalConstant.RECORD_STATUS_ACTIVE);
     dmsDocumentDAO = null;
     return dmsDocument;

   }
  
  /**
   * Gets the active and inactive dmsDocument by document ID.
   * 
   * @param documentID              The target dmsDocument ID
   * @return DmsDocument            The (DmsDocument) that met the doucmentID
   * @throws ApplicationException   Throws when operation fault or no record found
   * @see com.dcivision.dms.bean.DmsDocument
   */
  
  public synchronized DmsDocument getActiveInactiveDoc(Integer documentID) throws ApplicationException {
     DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
     DmsDocument dmsDocument = (DmsDocument) dmsDocumentDAO.getActiveInactiveByID(documentID);
     dmsDocumentDAO = null;
     return dmsDocument;
   }

  /**
   *  Gets the all document details by document ID.
   *
   *  @param      documentID               The target dmsDocument ID
   *  @return     List                     The (List) that consists of all the corresponding details info
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized List getDocumentDetailList(Integer documentID) throws ApplicationException {
    DmsDocumentDetailDAObject docDetailDAO = new DmsDocumentDetailDAObject(sessionContainer, conn);
    List docDetailList = docDetailDAO.getListByDocumentID(documentID);
    docDetailDAO = null;
    return docDetailList;
  }


  /**
   * Gets the active and inactive document details by document ID.
   * 
   * @param documentID             The target dmsDocument ID
   * @return List                  List that consists of all the corresponding detail info
   * @throws ApplicationException  Thrors when operation fault
   */
  public synchronized List getDocumentDetailListActiveInactive(Integer documentID) throws ApplicationException {
    DmsDocumentDetailDAObject docDetailDAO = new DmsDocumentDetailDAObject(sessionContainer, conn);
    List docDetailList = docDetailDAO.getListByDocumentIDActiveInactive(documentID);
    docDetailDAO = null;
    return docDetailList;
  }

  /**
   *  Gets the all user defined fields.
   *
   *  @param      userDefinedFieldID       The target user defined field ID
   *  @return     List                     The (List) that consists of all the corresponding details info
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized List getUDFDetailList(Integer userDefinedFieldID) throws ApplicationException {
    SysUserDefinedIndexDetailDAObject udfDetailDAObject = new SysUserDefinedIndexDetailDAObject(sessionContainer, conn);
    List udfDetailList = udfDetailDAObject.getListBySysUserDefinedIndexID(userDefinedFieldID);
    udfDetailDAObject = null;
    return udfDetailList;
  }

  /**
   *  Get the user defined field object.
   *
   *  @param      udfID                    The target user defined field ID
   *  @return     SysUserDefinedIndex      The (SysUserDefinedIndex) that consists of all the corresponding details info
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.framework.bean.SysUserDefinedIndex 
   */
  public synchronized SysUserDefinedIndex getUDF(Integer udfID) throws ApplicationException {
    SysUserDefinedIndexDAObject udfDAObject = new SysUserDefinedIndexDAObject(sessionContainer, conn);
    SysUserDefinedIndex udf = (SysUserDefinedIndex) udfDAObject.getObjectByID(udfID);
    udfDAObject = null;
    return udf;
  }

  /**
   *  Get the document's profile name
   *
   *  @param      documentID                    The target document ID
   *  @return     udfName                       The target document  udfName
   *  @see        com.dcivision.framework.bean.SysUserDefinedIndex 
   */
  public synchronized String  getUserDefinedTypeByDocumentID(Integer documentID){
    String udfName = "";
    String udfID = null;
    try{
      SysUserDefinedIndexDAObject udfDAObject = new SysUserDefinedIndexDAObject(sessionContainer, conn);
      List docDetailList = this.getDocumentDetailList(documentID);
      if (docDetailList!=null && docDetailList.size()>0){      
        udfID = String.valueOf(((DmsDocumentDetail)docDetailList.get(0)).getUserDefinedFieldID());      
        if(udfID != null){
          SysUserDefinedIndex udf = (SysUserDefinedIndex) udfDAObject.getObjectByID(TextUtility.parseIntegerObj(udfID));
          udfName = udf.getUserDefinedType();
        }
      }
      udfDAObject = null;
    }catch(Exception e){
      log.debug(e);
    }
    
    return udfName;    
  }
  
    
  
  /**
   *  Gets the  user defined field detail object.
   *
   *  @param      udfDetailID               The target user defined field detail ID
   *  @return     SysUserDefinedIndexDetail The (SysUserDefinedIndexDetail) that consists of the corresponding details info
   *  @throws     ApplicationException      Throws when operation fault
   *  @see        com.dcivision.framework.bean.SysUserDefinedIndexDetail
   */
  public synchronized SysUserDefinedIndexDetail getUDFDetail(Integer udfDetailID) throws ApplicationException {
    SysUserDefinedIndexDetailDAObject udfDetailDAObject = new SysUserDefinedIndexDetailDAObject(sessionContainer, conn);
    SysUserDefinedIndexDetail udfDetail = (SysUserDefinedIndexDetail) udfDetailDAObject.getObjectByID(udfDetailID);
    udfDetailDAObject = null;
    return udfDetail;
  }

  /**
   *  Gets the document Detail using document ID and the UDF detail ID.
   *
   *  @param      docID                    The target doucment ID
   *  @param      userDefinedFieldID       The target user defined field ID
   *  @return     List                     The dmsDocumentDetail
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.dms.bean.DmsDocumentDetail
   */
  public synchronized DmsDocumentDetail getDetailObjectByDocIDUDFDetailID(Integer docID, Integer udfDetailID) throws ApplicationException {
    DmsDocumentDetailDAObject docDetailDAO = new DmsDocumentDetailDAObject(sessionContainer, conn);
    DmsDocumentDetail docDetail = (DmsDocumentDetail) docDetailDAO.getObjectByDocumentIDUDFDetailID(docID, udfDetailID, GlobalConstant.RECORD_STATUS_ACTIVE);
    docDetailDAO = null;
    return docDetail;
  }

  /**
   *  Gets the all user defined index.
   *
   *  @return     List                     The (List) that consists of all the corresponding details info
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized List getUDFList() throws ApplicationException {
    SysUserDefinedIndexDAObject udfDAObject = new SysUserDefinedIndexDAObject(sessionContainer, conn);
    List udfList = udfDAObject.getListByObjectTypeStatus(GlobalConstant.OBJECT_TYPE_DOCUMENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    udfDAObject = null;
    return udfList;
  }

  /**
   *  Gets the user defined index.
   *
   *  @param      document                 The target document
   *  @return     SysUserDefinedIndex      SysUserDefinedIndex
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.framework.bean.SysUserDefinedIndex
   */
  public synchronized SysUserDefinedIndex getUserDefinedFieldByDocument(DmsDocument document) throws ApplicationException {
    SysUserDefinedIndexDAObject udfDAObject = new SysUserDefinedIndexDAObject(sessionContainer, conn);
    SysUserDefinedIndex udf = null;
    try {
      if (document.getUserDefinedFieldID() != null) {
        udf = (SysUserDefinedIndex) udfDAObject.getObjectByID(document.getUserDefinedFieldID());
      } else { //for case of have retrieve the userdefinedindexID
        List docDetailList = getDocumentDetailList(document.getID());
        if (!Utility.isEmpty(docDetailList)) {
          udf = (SysUserDefinedIndex) udfDAObject.getObjectByID( ( (DmsDocumentDetail) docDetailList.get(0)).getUserDefinedFieldID());
        }
      }
    } catch (Exception e) {
      log.error(e, e);
    }
    udfDAObject = null;
    return udf;
  }

  /**
   *  Gets the topest folder of that root.
   *
   *  @param rootID                         The root ID.
   *  @return                               The topest folder of that root.
   *  @throws ApplicationException          Throws when operation fault
   */
  public synchronized DmsDocument getRootFolderByRootID(Integer rootID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List list = dmsDocumentDAO.getListByParentID(new Integer(0), rootID, DmsDocument.FOLDER_TYPE);
    dmsDocumentDAO = null;
    if (Utility.isEmpty(list)) {
      return (null);
    } else {
      return ( (DmsDocument) list.get(0));
    }
  }

  /**
   *  Gets all document(s)/folder(s) under specified folder.
   *
   *  @param parentID   The parent ID
   *  @param rootID                         The root ID.
   *  @return List      The List that contains all the (DmsDocument)document(s)/ folder(s)
   *  @throws ApplicationException          Throws when operation fault
   */
  public synchronized List getDocumentListByParentIDRootID(Integer parentID, Integer rootID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List list = dmsDocumentDAO.getListByParentID(parentID, rootID);
    dmsDocumentDAO = null;
    if (Utility.isEmpty(list)) {
      return (new ArrayList());
    } else {
      return (list);
    }
  }

  /**
   * Gets active and inactive document under specifed folder.
   * 
   * @param parentID   The parent ID 
   * @param rootID     The root ID
   * @return           The List that contains all the (DmsDocuemnt) documents(s)/folder(s)
   * @throws ApplicationException
   */
  public synchronized List getInactiveDocumentListByParentIDRootID(Integer parentID, Integer rootID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List list = dmsDocumentDAO.getInactiveListByParentID(parentID, rootID);
    dmsDocumentDAO = null;
    if (Utility.isEmpty(list)) {
      return (new ArrayList());
    } else {
      return (list);
    }
  }

  /**
   *  Gets the dmsDocument list under the directory.
   *
   *  @param parentID                       The parentID of parent directory.
   *  @param rootID                         The rootID of root directory.
   *  @return                               The List of folders under that directory.
   *  @throws ApplicationException          Throws when list operation fault.
   */
  public synchronized List getFolderTreeByParentIDRootID(Integer parentID, Integer rootID) throws ApplicationException {
  	PermissionManager permManager = sessionContainer.getPermissionManager();
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List documentList = dmsDocumentDAO.getListByParentID(parentID, rootID, DmsDocument.FOLDER_TYPE);
    List tmpDocList = new ArrayList();
    List finalList = new ArrayList();
    List tmpList = null;
    for (int i=0; documentList != null && i<documentList.size(); i++){
    	DmsDocument doc = (DmsDocument)documentList.get(i);
    	if (permManager.hasAccessRight("D",doc.getID(),"R")){
    		tmpDocList.add(doc);
    	}
    }
    finalList.addAll(tmpDocList);
//    finalList.addAll(documentList);
    if (!Utility.isEmpty(documentList)) {
      for (int i = 0; i < documentList.size(); i++) {
        DmsDocument doc = (DmsDocument) documentList.get(i);
        tmpList = getFolderTreeByParentIDRootID(doc.getID(), doc.getRootID());
        if (!Utility.isEmpty(tmpList)) {
          finalList.addAll(tmpList);
        }
      }
    }
    dmsDocumentDAO = null;
    return finalList;
  }

  /**
   *  Gets the dmsDocument list under the directory.
   *
   *  @param parentID                       The parentID of parent directory.
   *  @param rootID                         The rootID of root directory.
   *  @return                               The List of (DmsDocument)folders under that directory.
   *  @throws ApplicationException          Throws when list operation fault.
   */
  public synchronized List getFolderByParentIDRootID(Integer parentID, Integer rootID) throws ApplicationException {
  	PermissionManager permManager = sessionContainer.getPermissionManager();
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List documentList = dmsDocumentDAO.getListByParentIDRecordStatus(parentID, rootID, DmsDocument.FOLDER_TYPE,GlobalConstant.RECORD_STATUS_ACTIVE);
    List finalList = new ArrayList();
    for (int i=0; documentList != null && i<documentList.size(); i++){
    	DmsDocument doc = (DmsDocument)documentList.get(i);
      if (permManager.hasAccessRight(conn,"D",doc.getID(),"R")){
    		finalList.add(doc);
    	}
    }    
//    finalList.addAll(documentList);
    return finalList;
  }
  
  public synchronized List getOnlyFolderByParentIDRootID(Integer parentID, Integer rootID) throws ApplicationException {
  	PermissionManager permManager = sessionContainer.getPermissionManager();
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List documentList = dmsDocumentDAO.getListByParentIDAndDocumentType(parentID, rootID, DmsDocument.FOLDER_TYPE,GlobalConstant.RECORD_STATUS_ACTIVE);
    List finalList = new ArrayList();
    for (int i=0; documentList != null && i<documentList.size(); i++){
    	DmsDocument doc = (DmsDocument)documentList.get(i);
      if (permManager.hasAccessRight(conn,"D",doc.getID(),"R")){
    		finalList.add(doc);
    	}
    }    
//    finalList.addAll(documentList);
    return finalList;
  }
  
  /**
   *  Gets the dmsDocument list under the directory.
   *
   *  @param parentID                       The parentID of parent directory.
   *  @param rootID                         The rootID of root directory.
   *  @param sortAttribute                  The order of list.
   *  @return                               The List of (DmsDocument)folders under that directory.
   *  @throws ApplicationException          Throws when list operation fault.
   */
  public synchronized List getFolderByParentIDRootID(Integer parentID, Integer rootID, String sortAttribute, String sortOrder) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List documentList = dmsDocumentDAO.getListByParentIDRecordStatus(parentID, rootID, DmsDocument.FOLDER_TYPE,GlobalConstant.RECORD_STATUS_ACTIVE,sortAttribute,sortOrder);
    List finalList = new ArrayList();
    finalList.addAll(documentList);
    return finalList;
  }

  /**
   *  Get the top version object by document id
   *
   *  @return     DmsVersion               The (DmsVersion) that is the newest version of document
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.dms.bean.DmsVersion 
   */
  public synchronized DmsVersion getTopVersionByDocumentID(Integer docID) throws ApplicationException {
    DmsVersionDAObject dmsVersionDAO = new DmsVersionDAObject(sessionContainer, conn);
    DmsVersion dmsVersion = (DmsVersion) dmsVersionDAO.getTopVersionByDocumentID(docID);
    dmsVersionDAO = null;
    return dmsVersion;
  }

  /**
   *  Get all (DmsVersion) objects of a given document id
   *
   *  @return     List                      List of version available for the given document
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized List getVersionListByDocumentID(Integer docID) throws ApplicationException {
    DmsVersionDAObject dmsVersionDAO = new DmsVersionDAObject(sessionContainer, conn);
    List versionList = dmsVersionDAO.getVersionsListByDocumentID(docID, "ASC");
    dmsVersionDAO = null;
    return versionList;
  }

  /**
   *  Get all (MtmDocumentVersion) objects of a given document id
   *
   *  @return     List                      List of version available for the given document
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.dms.bean.MtmDocumentVersion
   */
  public synchronized List getMtmDocumentVersionListByDocumentID(Integer docID) throws ApplicationException {
    MtmDocumentVersionDAObject dmsMtmDocumentVersionDAO = new MtmDocumentVersionDAObject(sessionContainer, conn);
    List mtmDocumentVersionList = dmsMtmDocumentVersionDAO.getListByDocumentID(docID);
    dmsMtmDocumentVersionDAO = null;
    return mtmDocumentVersionList;
  }

  /**
   *  Gets the corresponding version object by version id.
   *
   *  @return     DmsVersion               The (DmsVersion) that is the target version
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.dms.bean.DmsVersion
   */
  public synchronized DmsVersion getVersionByVersionID(Integer versionID) throws ApplicationException {
    DmsVersionDAObject dmsVersionDAO = new DmsVersionDAObject(sessionContainer, conn);
    DmsVersion dmsVersion = (DmsVersion) dmsVersionDAO.getObjectByID(versionID);
    dmsVersionDAO = null;
    return dmsVersion;
  }

  /**
   *  Get content object by content id.
   *
   *  @return     DmsContent               The (DmsContent) that is the target Content object
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized DmsContent getContentByContentID(Integer id) throws ApplicationException {
    DmsContentDAObject dmsContentDAO = new DmsContentDAObject(sessionContainer, conn);
    DmsContent dmsContent = (DmsContent) dmsContentDAO.getObjectByID(id);
    dmsContentDAO = null;
    return dmsContent;
  }

  /**
   *  Gets a document by document name, parentID and creatorID.
   *
   *  @param      name                     The target dmsDocument name
   *  @param      parentID                 The target dmsDocument parent id
   *  @param      creatorID                The target dmsDocument creator id
   *  @return     DmsDocument              The (DmsDocument) that met the documentID
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized DmsDocument getDocumentByNameParentIDCreatorID(String name, Integer parentID, Integer creatorID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsDocument dmsDocument = dmsDocumentDAO.getDocumentByNameParentIDCreatorID(name, parentID, creatorID);
    dmsDocumentDAO = null;
    return dmsDocument;
  }

  /**
   *  Gets a document by document name and parentID.
   *
   *  @param      name                     The target dmsDocument name
   *  @param      parentID                 The target dmsDocument parent id
   *  @return     DmsDocument              The (DmsDocument) that met the documentID
   *  @throws     ApplicationException     Throws when operation fault
   */
  public synchronized DmsDocument getDocumentByNameParentID(String name, Integer parentID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsDocument dmsDocument = dmsDocumentDAO.getDocumentByNameParentID(name, parentID);
    dmsDocumentDAO = null;
    return dmsDocument;
  }

  public synchronized DmsDocument getDocumentByNameParentID(String name, Integer parentID,String documentType ) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsDocument dmsDocument = dmsDocumentDAO.getDocumentByNameParentID(name, parentID, documentType);
    dmsDocumentDAO = null;
    return dmsDocument;
  }
  
  /**
   *  Search the document(s) by the search form (ListDmsDocumentForm) and List of rootID
   *
   *  @param searchForm
   *  @param rootIDs
   *  @return List List of result (DmsDocument) that match the search Form criteria and rootIDs
   *  @throws ApplicationException
   */
  public synchronized List searchDocumentBySearchObject(ListDmsDocumentForm searchForm, List rootIDs) throws ApplicationException {
	  	List resultList = new ArrayList();    
	  	DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
	  	if (DmsOperationConstant.ATTR_SEARCH_OPERATION.equals(searchForm.getAdvSearchOpt())) {
	  		if("OR".equals(searchForm.getIgnoreDuplicateShortcut())){
	  			//1.get the not duplic ShortCut and document's idstr  		
	  			List tmpIDList = new ArrayList();	
	  			String documentIDs ="";
	  			tmpIDList = dmsDocumentDAO.getAdvanceSearchDocumentIDListIgnoreDuplicShortcut(searchForm, rootIDs,"",1);
	  			if(!Utility.isEmpty(tmpIDList)){
	  				for(int i = 0 ; i < tmpIDList.size();i ++){
	  					if(i != 0){
	  						documentIDs += ",";	
	  					}
	  					documentIDs += tmpIDList.get(i).toString();     	
	  				}
	  			}
	  			//2.use the ids get the real search result      
	  			resultList = dmsDocumentDAO.getAdvanceSearchDocumentIDListIgnoreDuplicShortcut(searchForm, rootIDs,documentIDs,2);
	  		}else{
	  			resultList = dmsDocumentDAO.getAdvanceSearchList(searchForm, rootIDs);
	  		}
	  	} else if (DmsOperationConstant.KEYWORD_SEARCH_OPERATION.equals(searchForm.getAdvSearchOpt())) {
	  	}
	  	dmsDocumentDAO = null;
	  	return resultList;
  }

  /**
   *  Searchs the document(s) by the (ListDmsDocumentForm)searchForm, List of (ListDmsDocumentForm)searchForm and List of rootID
   *  and used for the bulk search function.
   *
   *  @param searchForm
   *  @param List List of (ListDmsDocumentForm)searchForm
   *  @param rootIDs
   *  @return List List of result (DmsDocument) that match the search Form criteria and rootIDs
   *  @throws ApplicationException
   */
  public synchronized List searchDocumentByImportFile(ListDmsDocumentForm searchForm, List searchFormList, List rootIDs) throws ApplicationException {
    List resultList = new ArrayList();
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    resultList = dmsDocumentDAO.getListByImportSearchObjectList(searchForm, rootIDs, searchFormList);
    dmsDocumentDAO = null;
    return resultList;
  }

  /**
   *  Gets the location path of the document or folder.
   *
   *  @param parentID
   *  @return location path of the document or folder
   *  @throws ApplicationException
   */
  public synchronized String getLocationPath(Integer parentID) throws ApplicationException {
    String path = "";
    if (parentID == null) {
      return ("");
    }

    while (parentID.intValue() != 0) {
      DmsDocument doc = this.getDocument(parentID);
      if (doc == null) {
        break;
      }
      path = FILE_SEPARATOR + doc.getDocumentName() + path;
      parentID = doc.getParentID();
    }

    if (path.length() > 0) {
      path = path.substring(1);
    }

    return (path);
  }

  /**
   *  Get the document details from request.
   *
   *  @param      request                  HttpServletRequest
   *  @return     List                     The docDetailsList retrieved from jsp
   */
  public synchronized List retrievalDocumentDetailsList(HttpServletRequest request) {
    List docDetailsList = new java.util.ArrayList();
    java.util.HashMap docDetailMap = new java.util.HashMap();
    for (java.util.Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
      String paraName = (String) e.nextElement();
      if (paraName.indexOf("udfDetailID_") >= 0) {
        //log.debug("paraName: " + paraName);

        Integer udfdetailID = Integer.valueOf(paraName.substring(paraName.lastIndexOf("_") + 1), 10);
        DmsDocumentDetail dmsDocumentDetail = new DmsDocumentDetail();
        dmsDocumentDetail.setUserDefinedFieldID(TextUtility.parseIntegerObj(request.getParameter("userDefinedFieldID")));
        dmsDocumentDetail.setUserDefinedFieldDetailID(udfdetailID);
        //Field Type
        String fieldType = request.getParameter("udfDetail_FieldType_" + udfdetailID);
        dmsDocumentDetail.setFieldType(fieldType);
        //Search Option
        String searchOpt = request.getParameter("udfDetail_Option_" + udfdetailID);
//        String searchOpt=dmsDocumentDetail.getSearchOption();
        if (!Utility.isEmpty(request.getParameter("udfDetail_Option_" + udfdetailID))) {
          searchOpt = request.getParameter("udfDetail_Option_" + udfdetailID);
        } else {
          searchOpt = dmsDocumentDetail.getSearchOption();
        }
        dmsDocumentDetail.setSearchOption(searchOpt);

        //ExcatMatch
        String excatMatch = request.getParameter("udfDetail_StringExactMatch_" + udfdetailID);
        dmsDocumentDetail.setExactMatch(TextUtility.parseBoolean(excatMatch));
        //UDF String Value
        String stringValue = request.getParameter("udfDetail_String_" + udfdetailID);
        if (!Utility.isEmpty(stringValue)){
          dmsDocumentDetail.setFieldValue(stringValue);
        }
        //UDF SDB Value
        String sDBValue = request.getParameter("udfDetail_SDB_" + udfdetailID);
        if (!Utility.isEmpty(sDBValue)){
          dmsDocumentDetail.setFieldValue(sDBValue);
        }

        //UDF Date Value
        String dateValue = request.getParameter("udfDetail_Date_" + udfdetailID);

        if (!Utility.isEmpty(dateValue) && !"null".equals(dateValue)) {
          dmsDocumentDetail.setDateValue(parseTimestamp(dateValue));

        }
        //UDF Date To Value
        String dateToValue = request.getParameter("udfDetail_DateTo_" + udfdetailID);
        if (!Utility.isEmpty(dateToValue) && !"null".equals(dateToValue)) {
          dmsDocumentDetail.setToDateValue(parseTimestamp(dateToValue));

        }
        //UDF Number Value
        String numberValue = request.getParameter("udfDetail_Number_" + udfdetailID);
        if (!Utility.isEmpty(numberValue)) {
          dmsDocumentDetail.setNumericValue(TextUtility.parseDoubleObj(
            numberValue));
        }
        //UDF Number To Value
        String numberToValue = request.getParameter("udfDetail_NumberTo_" + udfdetailID);
        if (!Utility.isEmpty(numberToValue)) {
          dmsDocumentDetail.setToNumericValue(TextUtility.parseDoubleObj(numberToValue));
        }
        dmsDocumentDetail.setRecordStatus("A");
        docDetailsList.add(dmsDocumentDetail);
      }

    }
    //log.debug("docDetailsList size: " + docDetailsList.size());
    return (docDetailsList);
  }

  /**
   *  Parse the temp datetime string from request for UDF details
   *
   *  @param      inStr                    The UDF detail datetime str
   *  @return     Timestamp                The Timestamp
   *  @throws
   */
  public synchronized Timestamp parseTimestamp(String inStr) {
    if (com.dcivision.framework.Utility.isEmpty(inStr)) {
      return (null);
    }
    java.util.Date tmpDate = null;
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DmsOperationConstant.HIDDEN_DATETIME_FORMAT, new java.util.Locale("en", "US"));
    try {
      tmpDate = sdf.parse(inStr);
      return (new Timestamp(tmpDate.getTime()));
    } catch (java.text.ParseException pe) {
      log.error(pe, pe);
      return (null);
    }
  }

  /**
   * Convert the time String from date Picker to Timestamp
   * @param inStr time String from date Picker
   * @return Timestamp of correponding string from datePicker
   */
  public synchronized Timestamp parseDatePickerTimestamp(String inStr) {
    if (com.dcivision.framework.Utility.isEmpty(inStr)) {
      return (null);
    }
    java.util.Date tmpDate = null;
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DATE_FORMAT));
    try {
      tmpDate = sdf.parse(inStr);
      return (new Timestamp(tmpDate.getTime()));
    } catch (java.text.ParseException pe) {
      log.error(pe, pe);
      return (null);
    }
  }

  /**
   *  Gets the DmsDocument List from Lucene hits results
   *
   *  @param      searchForm               The current form name
   *  @param      hits                     The hit objects
   *  @return     List                     The DmsDocument List of result
   *  @throws     Exception
   */
  public synchronized List retrieveDmsDocListFromLuceneDocList(ListDmsDocumentForm searchForm, Hits hits) throws Exception {
    List result = new ArrayList();
    
    List noDuplicateDocList = new ArrayList();    

    //remove the duplicate doc and save the doc to a new  list
    for (int i = 0; i < hits.length(); i++) {
      Document doc = hits.doc(i);      
      if(!noDuplicateDocList.contains(TextUtility.parseIntegerObj(doc.get("DCI_ID")))){
        noDuplicateDocList.add(TextUtility.parseIntegerObj(doc.get("DCI_ID")));        
      }        
    }
    
    
    
    int totalNumOfRecord = noDuplicateDocList.size();
    int rowLoopCnt = 0;

    
    
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    if (DmsOperationConstant.SEARCH_RESULT_ALL.equals(searchForm.
      getSearchResultOpt())) {
      startOffset = 0;
    }
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    try{
      if (!DmsOperationConstant.SEARCH_RESULT_ALL.equals(searchForm.
          getSearchResultOpt())) {
        while (rowLoopCnt < pageSize && startOffset <= noDuplicateDocList.size()) {
          //log.debug("start off set = " + new Integer(startOffset - 1));          
          Integer docID = (Integer)noDuplicateDocList.get(startOffset - 1);          
          DmsDocument tmpDmsDocument = new DmsDocument();
          try {
          	tmpDmsDocument = this.getDocument(docID);
            if(tmpDmsDocument != null){//barbin 2006-5-29
               //tmpDmsDocument.setRecordCount(totalNumOfRecord);//Update By Jim.Zhou		2006/07/14		Bug	#5767
               tmpDmsDocument.setRowNum(startOffset++);
               ++rowLoopCnt;
               result.add(tmpDmsDocument);
            }//Add By Jim.Zhou		2006/07/14		Bug	#5767
            else{
            	totalNumOfRecord --;
              ++rowLoopCnt;
            }
            //Add End
          } catch (ApplicationException e) {
            log.error(e, e);
  				}
        } 
      	
        //Add By Jim.Zhou		2006/07/14		Bug	#5767
      	for (int i = 0; i < result.size(); i++){
      		((DmsDocument)result.get(i)).setRecordCount(totalNumOfRecord);
      	}
      	//Add End
        
      } else {
        for (int i = 0; i < noDuplicateDocList.size(); i++) {
          Integer docID = (Integer)noDuplicateDocList.get(i);          
          DmsDocument tmpDmsDocument;

          tmpDmsDocument = this.getDocument(docID);
          if(tmpDmsDocument !=null){
        	  if (DmsDocument.DOCUMENT_LINK.equals(tmpDmsDocument.getDocumentType())||DmsDocument.PAPER_DOC_TYPE.equals(tmpDmsDocument.getDocumentType())){
                  totalNumOfRecord = totalNumOfRecord - 1;
              }
            if (!DmsDocument.DOCUMENT_LINK.equals(tmpDmsDocument.getDocumentType())&&!DmsDocument.PAPER_DOC_TYPE.equals(tmpDmsDocument.getDocumentType())){
                tmpDmsDocument.setRecordCount(totalNumOfRecord);
                tmpDmsDocument.setRowNum(i + 1);
                result.add(tmpDmsDocument);
            }
          }
         
        }
      }
    }catch(ApplicationException apx){
      log.error(apx.toString());
    }
    return result;
  }

  /**
   *  Gets the archieved list (all versions) using document ID and archive ID
   *
   *  @param      documentID               The target document ID
   *  @param      archiveID                The target archive ID
   *  @return     List                     The DmsVersion List of result
   *  @throws     ApplicationException
   */
  public synchronized List getArchivedListByDocumentIDArchiveID(Integer documentID, Integer archiveID) throws ApplicationException {
    DmsVersionDAObject versionDAO = new DmsVersionDAObject(sessionContainer, conn);
    List resultList = new ArrayList();
    resultList = versionDAO.getVersionsListByDocumentIDArchiveID(documentID, archiveID);
    versionDAO = null;
    return resultList;
  }
  
  public synchronized InputStream getDataInputStreamByDocument(DmsDocument document) throws ApplicationException {
    DmsVersion version = this.getTopVersionByDocumentID(document.getID());
    DmsContentDAObject contentDAO = new DmsContentDAObject(this.sessionContainer, this.conn);
    DmsContent content = (DmsContent)contentDAO.getObjectByID(version.getContentID());
    return this.getDataInputStreamByDocument(document, version, content);
  }

  /**
   *  Retrieves the inputStream of target document from ParaDoc
   *
   *  @param      document                 The DmsDocument object of target document
   *  @param      version                  The DmsVersion object of target version
   *  @param      content                  The DmsContent object of target content
   *  @return     InputStream              The InputStream object of target document in ParaDoc
   *  @throws     ApplicationException
   */
  public synchronized InputStream getDataInputStreamByDocument(DmsDocument document, DmsVersion version, DmsContent content) throws ApplicationException {
    DmsContentManager dmsContentManager = new DmsContentManager(sessionContainer, conn);
    return dmsContentManager.readDmsDocumentStoreContent(document,content);
  }

  /**
   * Determine the function code that the document is in personal folder or public folder funtion module 
   *
   * @param document
   * @return function code of PERSONAL FOLDER OR PUBLIC FOLDER
   * @throws ApplicationException
   */

  public synchronized String getCurFunctionCode(DmsDocument document) throws ApplicationException {
    String sCurFunctionCode = "";
    DmsDocument documentRoot = this.getRootFolderByRootID(document.getRootID());
    if (documentRoot != null) {
      if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(documentRoot.getDocumentName())) {
        sCurFunctionCode = SystemFunctionConstant.DMS_PERSONAL_FOLDER;
      } else {
        sCurFunctionCode = SystemFunctionConstant.DMS_PUBLIC_FOLDER;
      }
    }
    return sCurFunctionCode;
  }

  /**
   *  Get and set the default document profile into session DmsOperationConstant.DMS_DEFAULT_PROFILE_SETTING
   *
   *  @param      request                  The HttpServletRequest
   *  @return     List                     The default profile list
   *  @throws     ApplicationException
   *  @see        com.dcivision.dms.DmsOperationConstant
   */
  public synchronized List checkNSetDefaultProfileList(HttpServletRequest request) throws ApplicationException {
    // Retrieve the default document profile settings.
    List dmsDefaultProfile = null;
  //  if (request.getSession().getServletContext().getAttribute(DmsOperationConstant.DMS_DEFAULT_PROFILE_SETTING) != null) {
  if (!Utility.isEmpty(request.getSession().getServletContext().getAttribute(DmsOperationConstant.DMS_DEFAULT_PROFILE_SETTING)) ) {
      dmsDefaultProfile = (List) request.getSession().getServletContext().getAttribute(DmsOperationConstant.DMS_DEFAULT_PROFILE_SETTING);
    } else {
      org.apache.struts.config.ModuleConfig modConfig = org.apache.struts.util.RequestUtils.getModuleConfig(request, request.getSession().getServletContext());

      ValidatorResources validRes = (ValidatorResources) request.getSession().getServletContext().getAttribute(ValidatorPlugIn.VALIDATOR_KEY +
        modConfig.getPrefix());
      Form frm = validRes.getForm(sessionContainer.getSessionLocale(), "maintDmsDocumentForm");
      Form frm2 = validRes.getForm(sessionContainer.getSessionLocale(), "maintDmsCompoundDocumentForm");
      int totalFieldCount = Integer.parseInt(com.dcivision.framework.SystemParameterFactory.getSystemParameter(com.dcivision.framework.SystemParameterConstant.
        DMS_DEFAULT_PROFILE_FIELD_COUNT));

      com.dcivision.dms.dao.DmsDefaultProfileSettingDAObject dmsProfileDAO = new com.dcivision.dms.dao.DmsDefaultProfileSettingDAObject(null, conn);
      dmsDefaultProfile = dmsProfileDAO.getFullList();
      for (int i = 0; i < totalFieldCount; i++) {
        DmsDefaultProfileSetting setting = (DmsDefaultProfileSetting) dmsDefaultProfile.get(i);
        if (!Utility.isEmpty(setting.getFieldLabel())) {
          setting.setFieldName(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), setting.getFieldLabel()));
        }

        Field fld = new Field();
        Arg arg = new Arg();
        arg.setResource(false);
        arg.setKey(setting.getFieldName());
        fld.setProperty("userDef" + (i + 1));
        fld.addArg(arg);

        String depends = "";
        if (GlobalConstant.TRUE.equals(setting.getMandatoryFlag())) {
          depends = "required";
          

        }

        if (DmsDefaultProfileSetting.FIELD_TYPE_INTEGER.equals(setting.getFieldType())) {
          depends += Utility.isEmpty(depends) ? "integer" : ",integer";
        } else if (DmsDefaultProfileSetting.FIELD_TYPE_FLOAT.equals(setting.getFieldType())) {
          depends += Utility.isEmpty(depends) ? "float" : ",float";
        }

        if (!Utility.isEmpty(depends)) {
          fld.setDepends(depends);
      
          if(frm.containsField(fld.getProperty())){
            frm.getField(fld.getProperty()).setDepends(depends);
          }else{
            frm.addField(fld);
          }
          
          if(frm2.containsField(fld.getProperty())){
             frm2.getField(fld.getProperty()).setDepends(depends);
          }else{
             frm2.addField(fld);
          }
  
        }else{
          depends=depends==null?"":depends;
          if(frm.getField(fld.getProperty())!=null){
            frm.getField(fld.getProperty()).setDepends(depends);
          }
          if(frm2.getField(fld.getProperty())!=null){
            frm2.getField(fld.getProperty()).setDepends(depends);
          }
        }
      }
      request.getSession().getServletContext().setAttribute(DmsOperationConstant.DMS_DEFAULT_PROFILE_SETTING, dmsDefaultProfile);
      dmsProfileDAO = null;
    }

    return dmsDefaultProfile;
  }


  /**
   * Gets all the document related information i.e. document details and update alerts
   * 
   * @param documentID
   * @return MaintDmsDocumentForm form object
   * @throws ApplicationException
   */
  public synchronized MaintDmsDocumentForm getAllDocumentRelatedInfo(Integer documentID) throws ApplicationException {
    MaintDmsDocumentForm maintDmsDocumentForm = new MaintDmsDocumentForm();
    DmsDocument document = getDocument(documentID);
    Integer inviteTypeID = null;
    //Set common document info
    List docDetailList = getDocumentDetailList(documentID);
    if (docDetailList != null) {
      maintDmsDocumentForm.setFormData(document, docDetailList);
    } else {
      maintDmsDocumentForm.setFormData(document);
    }
    maintDmsDocumentForm.setCurFunctionCode(this.getCurFunctionCode(document));

    //Use for List the target User Defined Fields Detail
    if (maintDmsDocumentForm.getUserDefinedFieldID() != null) {
      SysUserDefinedIndex udfIndex = this.getUDF(TextUtility.parseIntegerObj(maintDmsDocumentForm.getUserDefinedFieldID()));
      if (udfIndex != null) {
        maintDmsDocumentForm.setUserDefinedType(udfIndex.getUserDefinedType());
        List udfDetailList = getUDFDetailList(TextUtility.parseIntegerObj(maintDmsDocumentForm.getUserDefinedFieldID()));
        maintDmsDocumentForm.setUdfDetailList(udfDetailList);
      }
    }

    /* Used to retrieval all alert info and version info for Document Summary Page */
    VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
    int versions = versionControlManager.getTotalVerionsByDocumentID(documentID);
    if (versions > 0) {
      maintDmsDocumentForm.setNoOfVersion(versions);
    }
    versionControlManager.release();

    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, conn);
    UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, conn);
    List typeList = new ArrayList();

    //Retirqval the update alert for both invitation and edit
    UpdateAlert updateAlertInvite = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, documentID, sessionContainer.getUserRecordID(),
      UpdateAlert.INVITE_TYPE);
    UpdateAlert updateAlertEdit = (UpdateAlert) updateAlertDAO.getByObjectTypeObjectIDCreatorID(GlobalConstant.OBJECT_TYPE_DOCUMENT, documentID, sessionContainer.getUserRecordID());

    /* Check for document alert invitation */
    if (updateAlertInvite != null) {
      typeList = updateAlertTypeDAO.getByUpdateAlertIDByOwnerID(updateAlertInvite.getID(), UpdateAlert.INVITE_TYPE, sessionContainer.getUserRecordID());
      // set action type
      if (!Utility.isEmpty(typeList)) {
        String actionType = "";
        for (int i = 0; i < typeList.size(); ++i) {
          actionType = actionType + ( ( (UpdateAlertType) typeList.get(i)).getActionType()) + ";";
          if (i == 0) {
            maintDmsDocumentForm.setDueDate(TextUtility.formatTimestampToDate( ( (UpdateAlertType) typeList.get(i)).getDueDate()));
            maintDmsDocumentForm.setMessage( ( (UpdateAlertType) typeList.get(i)).getMessage());
            maintDmsDocumentForm.setNotifyWayI( ( (UpdateAlertType) typeList.get(0)).getNotifyWay());
            inviteTypeID = ( (UpdateAlertType) typeList.get(i)).getID();
          }
        }
        maintDmsDocumentForm.setActionTypeI(actionType);
      }

      //set Invite recipient lists
      AlertManager alertManager = new AlertManager(sessionContainer, conn);
      List userRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.USER_RECIPIENT);
      maintDmsDocumentForm.setUserList( Utility.getStringArray(userRecipientList));
      List groupRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.GROUP_RECIPIENT);
      maintDmsDocumentForm.setGroupList( Utility.getStringArray(groupRecipientList));
      List roleRecipientList = alertManager.getRecipientByUpdateAlertTypeID(inviteTypeID, UpdateAlert.ROLE_RECIPIENT);
      maintDmsDocumentForm.setRoleList( Utility.getStringArray(roleRecipientList));
      alertManager.release();
    }

    /* For Document Alert inquiry */
    if (updateAlertEdit != null) {

      typeList = updateAlertTypeDAO.getByUpdateAlertIDByOwnerID(updateAlertEdit.getID(), sessionContainer.getUserRecordID());
      // set action type
      if (!Utility.isEmpty(typeList)) {
        String actionsType = "";
        for (int i = 0; i < typeList.size(); ++i) {
          actionsType = actionsType + ( ( (UpdateAlertType) typeList.get(i)).getActionType()) + ";";
          if (i == 0) {
            maintDmsDocumentForm.setNotifyWayA( ( (UpdateAlertType) typeList.get(0)).getNotifyWay());
          }
        }
        maintDmsDocumentForm.setActionTypeA(actionsType);
      }
    }
    /*Retrieval document detail info end */
    updateAlertDAO = null;
    updateAlertTypeDAO = null;

    return maintDmsDocumentForm;
  }


  /**
   * Gets all the folders under specified root and
   * gets all Compound documents and paper documents under specified root if compound documnent
   * and paper document is allowed in the system.
   * 
   * @param listDmsDocumentForm
   * @param rootIDs
   * @return List of folders (include compound document and paper document if system allowed)
   * @throws ApplicationException
   */
  public synchronized List getDmsFolderListByDocumentTypeRootIDLists(ListDmsDocumentForm listDmsDocumentForm, List rootIDs) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List resultList = dmsDocumentDAO.getDmsFolderListByRootIDLists(listDmsDocumentForm, rootIDs);
    dmsDocumentDAO = null;
    return resultList;
  }

  /**
   * Count No. of the files under the root folder
   *
   * @status  record status of the file
   * @rootFolderID  the id of the root folder
   * @return  total no. of the file
   */

  public synchronized Integer totalNoOfFileUnderRoot(String recordStatus, Integer rootFolderID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    Integer totalNoOfFile = dmsDocumentDAO.getNoOfFileUnderRoot(recordStatus, rootFolderID);
    dmsDocumentDAO = null;
    return totalNoOfFile;

  }

  /**
   * Summation file size under the root folder
   *
   * @status  record status of the file
   * @rootFolderID  the id of the root folder
   * @return  total file size
   */
  public synchronized Double totalFileSizeUnderRoot(String recordStatus, Integer rootFolderID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    Double totalFileSize = dmsDocumentDAO.getTotalFileSizeUnderRoot(recordStatus, rootFolderID);
    dmsDocumentDAO = null;
    return totalFileSize;
  }

  /**
   *  Get all (MtmDocumentRelation) objects of a given document id
   *
   *  @return     List                     List of (MtmDocumentRelation) objects of the given document
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.dms.bean.MtmDocumentRelationship
   */
  public synchronized List getMtmDocuemntRelationshipListByDocumentID(Integer docID, String relationType) throws ApplicationException {
    MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
    List mtmDocumentRelationshipList = dmsMtmDocumentRelationshipDAO.getListByIDRelationType(docID, relationType);
    List mtmDocumentIndirectRelationshipList = dmsMtmDocumentRelationshipDAO.getListByRelationIDRelationType(docID, relationType);
    List documentRelationList = new ArrayList();
    MtmDocumentRelationship relationObj = null;
    DmsDocument dmsDocument = null;

    if (!Utility.isEmpty(mtmDocumentRelationshipList)) {
      for (int i = 0; i < mtmDocumentRelationshipList.size(); i++) {
        relationObj = (MtmDocumentRelationship) mtmDocumentRelationshipList.get(i);
        try{
        dmsDocument = this.getDocument(relationObj.getRelatedDocumentID());
        relationObj.setRootID(dmsDocument.getRootID());
        relationObj.setParentID(dmsDocument.getParentID());
        relationObj.setRelationshipDirection(MtmDocumentRelationship.DOCUMENT_RELATION_DIRECT);
        relationObj.setDocumentName(dmsDocument.getDocumentName());
        documentRelationList.add(relationObj);
        }catch(ApplicationException aex){
          //ignore
        }
      }
    }
    //add the indirect relationship type to the document list
    if (!Utility.isEmpty(mtmDocumentIndirectRelationshipList)) {
      for (int j = 0; j < mtmDocumentIndirectRelationshipList.size(); j++) {
        relationObj = (MtmDocumentRelationship) mtmDocumentIndirectRelationshipList.get(j);
        try{
        
          dmsDocument = this.getDocument(relationObj.getRelatedDocumentID());
          relationObj.setRootID(dmsDocument.getRootID());
          relationObj.setParentID(dmsDocument.getParentID());
          relationObj.setRelationshipDirection(MtmDocumentRelationship.DOCUMENT_RELATION_INDIRECT);
          relationObj.setDocumentName(dmsDocument.getDocumentName());
          documentRelationList.add(relationObj);
        }catch(ApplicationException aex){
          //ignore
        }
      }
    }

    dmsMtmDocumentRelationshipDAO = null;
    return documentRelationList;
  }

  /**
   * gets ancestor document(s) IDs  of a given document
   *
   * @CurrentDocumentId  the id of the given documdnt
   * @return  List of the ancestor document ID
   */
  public synchronized List getParentDocumentList(Integer CurrentDocumentID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);

    List parentDocumentIdList = new ArrayList();
    List tempParentDocumentIdList = null;
    if (CurrentDocumentID.intValue() != 0) {
      DmsDocument doc = (DmsDocument) dmsDocumentDAO.getObjectByID(CurrentDocumentID);

      if (doc.getParentID().intValue() != 0) {
        parentDocumentIdList.add(doc.getID());
        tempParentDocumentIdList = getParentDocumentList(doc.getParentID());
        if (!Utility.isEmpty(tempParentDocumentIdList)) {
          parentDocumentIdList.addAll(tempParentDocumentIdList);
        }
      }
    }
    dmsDocumentDAO = null;
    return parentDocumentIdList;
  }

  /**
 * Gets the navigation tree layout Script
   *
 * @param parentDocumentID  the parent ID of current document
 * @param CurrentDocumentID the ID of current document
 * @param rootID            the rootID of the current document
 * @param pageViewOption    the option of page view
 * @param jspPageMappingName the page of the tree node link
 * @return
 * @throws ApplicationException
   */
      
    public synchronized String getXloadTreeScriptByParentIDCurrentIdFinal(Integer parentDocumentID, Integer CurrentDocumentID, Integer rootID, String pageViewOption, String jspPageMappingName, String isUrl, String isShowShortCut, String isNewTree, String reserveParameter, String reserveParameter2) throws ApplicationException {
      String outScript = "";
      String tempString = "";
      DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
      List parentDocumentList = getParentDocumentList(CurrentDocumentID);
      List subDocumentList = null;
      List existParentDocumentList = new ArrayList();
      DmsDocument document = null;
      if (!Utility.isEmpty(parentDocumentList)) {
        for (int i = parentDocumentList.size() - 1; i > -1; i--) {
          Integer parentID = (Integer) parentDocumentList.get(i);
          subDocumentList = getFolderByParentIDRootID(parentID, rootID);
          if (!Utility.isEmpty(subDocumentList)) {
            if (parentDocumentID.intValue() != (parentID.intValue()) && !existParentDocumentList.contains(parentID)) {
              DmsDocument doc = (DmsDocument) dmsDocumentDAO.getObjectByID(parentID);
              existParentDocumentList.add(parentID);
              if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType())){//if is compound doc then add compoundIcon            
                tempString += "var subStaticNode" + doc.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(doc.getDocumentName()) +
                "', 'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                ",null,webFXTreeConfig.compoundIcon,webFXTreeConfig.openCompoundIcon) ;\n";
              }else if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){//if is paper doc then add paperIcon 
                tempString += "var subStaticNode" + doc.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(doc.getDocumentName()) +
                "', 'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                ",null,webFXTreeConfig.paperIcon,webFXTreeConfig.openPaperIcon) ;\n";
              }else if(DmsDocument.DOCUMENT_LINK.equals(doc.getDocumentType())){
                DmsDocument  newDocument = getRelationshipTargetDocument(doc.getID(),DmsDocument.DOCUMENT_LINK);
                if(!Utility.isEmpty(newDocument)){
                  tempString += "var subStaticNode" + doc.getID() + " = new WebFXTreeItem('" + TextUtility.escapeJSString(doc.getDocumentName()) + "', 'javascript:setHiddenValue(" + newDocument.getID() + ", " + rootID + ",\\'" + newDocument.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.shortcutFolder,webFXTreeConfig.shortcutFolder) ;\n";
                }  
              }else if(DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType())){//if is email doc then add emailIcon 
                  tempString += "var subStaticNode" + doc.getID() +
                  " = new WebFXTreeItem('" +
                  TextUtility.escapeJSString(doc.getDocumentName()) +
                  "', 'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                  ",null,webFXTreeConfig.emailIcon,webFXTreeConfig.openEmailIcon) ;\n";
              }else if(DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType())){//if is form doc then add formIcon 
                  tempString += "var subStaticNode" + doc.getID() +
                  " = new WebFXTreeItem('" +
                  TextUtility.escapeJSString(doc.getDocumentName()) +
                  "', 'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                  ",null,webFXTreeConfig.formIcon,webFXTreeConfig.openFormIcon) ;\n";
              }else if(DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType())){//if is workflow doc then add workflowIcon 
                  tempString += "var subStaticNode" + doc.getID() +
                  " = new WebFXTreeItem('" +
                  TextUtility.escapeJSString(doc.getDocumentName()) +
                  "', 'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                  ",null,webFXTreeConfig.workflowIcon,webFXTreeConfig.openWorkflowIcon) ;\n";
              }else{
                tempString += "var subStaticNode" + doc.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(doc.getDocumentName()) +
                "', 'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ") ;\n";
              
              }
              tempString += "subStaticNode" + doc.getParentID() +
                ".add(subStaticNode" + doc.getID() + ");\n";
              
            }
            for (int ii = 0; ii < subDocumentList.size(); ii++) {
              document = (DmsDocument) subDocumentList.get(ii);
              if (!parentDocumentList.contains(document.getID())) {
                List subFolderList = getFolderByParentIDRootID(document.getID(),
                  rootID);
                if (Utility.isEmpty(subFolderList)) {               
                  if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType())){//if is compound doc then add compoundIcon                
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "',  'javascript:setHiddenValue(" + document.getID() + ", " + 
                    rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + 
                    ",null,webFXTreeConfig.compoundIcon,webFXTreeConfig.openCompoundIcon) ;\n";
                  }else if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){//if is paper doc then add paperIcon
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "',  'javascript:setHiddenValue(" + document.getID() + ", " + 
                    rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + 
                    ",null,webFXTreeConfig.paperIcon,webFXTreeConfig.openPaperIcon) ;\n";
                  }else if(DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
                    DmsDocument  newDocument = getRelationshipTargetDocument(document.getID(),DmsDocument.DOCUMENT_LINK);
                    if(!Utility.isEmpty(newDocument)){
                      tempString += "var subStaticNode" + document.getID() +
                      " = new WebFXTreeItem('" +
                      TextUtility.escapeJSString(document.getDocumentName()) +
                      "',  'javascript:setHiddenValue(" + newDocument.getID() + ", " + 
                      newDocument.getRootID() + ",\\'" + newDocument.getDocumentType() +"\\')'," + document.getID() + 
                      ",null,webFXTreeConfig.shortcutFolder,webFXTreeConfig.shortcutFolder) ;\n";
                    } 
                  }else if(DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType())){//if is email doc then add emailIcon
                      tempString += "var subStaticNode" + document.getID() +
                      " = new WebFXTreeItem('" +
                      TextUtility.escapeJSString(document.getDocumentName()) +
                      "',  'javascript:setHiddenValue(" + document.getID() + ", " + 
                      rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + 
                      ",null,webFXTreeConfig.emailIcon,webFXTreeConfig.openEmailIcon) ;\n";
                  }else if(DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType())){//if is form doc then add formIcon
                      tempString += "var subStaticNode" + document.getID() +
                      " = new WebFXTreeItem('" +
                      TextUtility.escapeJSString(document.getDocumentName()) +
                      "',  'javascript:setHiddenValue(" + document.getID() + ", " + 
                      rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + 
                      ",null,webFXTreeConfig.formIcon,webFXTreeConfig.openFormIcon) ;\n";
                  }else if(DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType())){//if is workflow doc then add workflowIcon
                      tempString += "var subStaticNode" + document.getID() +
                      " = new WebFXTreeItem('" +
                      TextUtility.escapeJSString(document.getDocumentName()) +
                      "',  'javascript:setHiddenValue(" + document.getID() + ", " + 
                      rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + 
                      ",null,webFXTreeConfig.workflowIcon,webFXTreeConfig.openWorkflowIcon) ;\n";
                  }else{
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," +
                                      document.getID() + ") ;\n";
                      
                  }
                  tempString += "subStaticNode" + document.getParentID() +
                    ".add(subStaticNode" + document.getID() + ");\n";
                  
                } else {
                  tempString += "subStaticNode" + document.getParentID() +
                    ".add(rti = new WebFXLoadTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName())
                    + "', '"+ SystemParameterFactory.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL)  + "/dms/GetSubFolderXml.do?parentID=" + document.getID() +
                    "&rootID=" + rootID + "&type=locationSelect',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ")) ;\n";
                }
              } else {
                if ( (parentDocumentID.intValue() != (document.getID().intValue())) && !existParentDocumentList.contains(document.getID())) {
                  existParentDocumentList.add(document.getID());
                  if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType())){//if is compound doc then add compoundIcon                
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                    ",null,webFXTreeConfig.compoundIcon,webFXTreeConfig.openCompoundIcon) ;\n";
                  }else if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){//if is paper doc then add paperIcon
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                    ",null,webFXTreeConfig.paperIcon,webFXTreeConfig.openPaperIcon) ;\n";
                  }else if(DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
                    DmsDocument  newDocument = getRelationshipTargetDocument(document.getID(),DmsDocument.DOCUMENT_LINK);
                    if(!Utility.isEmpty(newDocument)){
                     tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + newDocument.getID() + ", " + newDocument.getRootID() + ",\\'" + newDocument.getDocumentType() +"\\')'," + document.getID() +
                              ",null,webFXTreeConfig.paperIcon,webFXTreeConfig.openPaperIcon) ;\n";
                    }
                  }else if(DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType())){//if is email doc then add emailIcon
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                    ",null,webFXTreeConfig.emailIcon,webFXTreeConfig.openEmailIcon) ;\n";
                  }else if(DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType())){//if is form doc then add formIcon
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                    ",null,webFXTreeConfig.formIcon,webFXTreeConfig.openFormIcon) ;\n";
                  }else if(DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType())){//if is workflow doc then add workflowIcon
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() +
                    ",null,webFXTreeConfig.workflowIcon,webFXTreeConfig.openWorkflowIcon) ;\n";
                  }else{
                    tempString += "var subStaticNode" + document.getID() +
                    " = new WebFXTreeItem('" +
                    TextUtility.escapeJSString(document.getDocumentName()) +
                    "','javascript:setHiddenValue(" + document.getID() + ", " + rootID + ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ") ;\n";
                  
                  }
                  tempString += "subStaticNode" + document.getParentID() +
                    ".add(subStaticNode" + document.getID() + ");\n";
                }
              }
            }
          } else {
            if (!existParentDocumentList.contains(parentID)) {
              document = (DmsDocument) dmsDocumentDAO.getObjectByID(parentID);
              if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType())){//if is compound doc then add compoundIcon            
                tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID +
                ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.compoundIcon,webFXTreeConfig.openCompoundIcon) ;\n";
              }else if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){//if is paper doc then add paperIcon
                tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID +
                ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.paperIcon,webFXTreeConfig.openPaperIcon) ;\n";
              }else if(DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
                DmsDocument  newDocument = getRelationshipTargetDocument(document.getID(),DmsDocument.DOCUMENT_LINK);
                if(!Utility.isEmpty(newDocument)){
                  tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + newDocument.getID() + ", " + newDocument.getRootID() +
                ",\\'" + newDocument.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.paperIcon,webFXTreeConfig.openPaperIcon) ;\n";
                }     
              }else if(DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType())){//if is email doc then add emailIcon
                tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID +
                ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.emailIcon,webFXTreeConfig.openEmailIcon) ;\n";
              }else if(DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType())){//if is form doc then add formIcon
                tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID +
                ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.formIcon,webFXTreeConfig.openFormIcon) ;\n";
              }else if(DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType())){//if is workflow doc then add workflowIcon
                tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID +
                ",\\'" + document.getDocumentType() +"\\')'," + document.getID() + ",null,webFXTreeConfig.workflowIcon,webFXTreeConfig.openWorkflowIcon) ;\n";
              }else{
                tempString += "var subStaticNode" + document.getID() +
                " = new WebFXTreeItem('" +
                TextUtility.escapeJSString(document.getDocumentName()) +
                "',  'javascript:setHiddenValue(" + document.getID() + ", " + rootID + ")'," + document.getID() + ",\\'" + document.getDocumentType() +"\\') ;\n";              
              }
              tempString += "subStaticNode" + document.getParentID() +
                ".add(subStaticNode" + document.getID() + ");\n";
            }
          }
        }
      }
      outScript = tempString;
      return outScript;
    }
  
  /**
   *  Gets DmsDocumentIndex object by document ID
   *
   *  @param      documentID               The target dmsDocument ID
   *  @return     DmsDocumentIndex         The (DmsDocumentIndex) that met the documentID
   *  @throws     ApplicationException     Throws when operation fault
   *  @see        com.dcivision.dms.bean.DmsDocumentIndex
   */
  public synchronized DmsDocumentIndex getDocumentIndexByDocID(Integer documentID) throws ApplicationException {
    DmsDocumentIndexDAObject dmsDocumentIndexDAO = new DmsDocumentIndexDAObject(sessionContainer, conn);
    DmsDocumentIndex dmsDocumentIndex = (DmsDocumentIndex) dmsDocumentIndexDAO.getIndexByDocID(documentID);
    dmsDocumentIndexDAO = null;
    return dmsDocumentIndex;

  }

  /**
   *  Gets the position of the user defined detail based on the sysUserDefinedDetail.
   *
   *  @param      userDefinedID              The user defined field ID of a given document
   *  @param      userDefinedID              The user defined field detail ID
   *  @return     pos                        The pos of user defined field detail
   *  @throws     ApplicationException     Throws when operation fault
   */

  public synchronized int getUDFDetailPos(Integer userDefinedID, Integer userDefinedDetailID) throws ApplicationException {
    int pos = 0;
    DmsDocumentDetailDAObject detailDAO = new DmsDocumentDetailDAObject(sessionContainer, conn);
    DmsDocumentDetail documentDetail = new DmsDocumentDetail();
    List detailList = detailDAO.getByUDFID(userDefinedID);
    for (int i = 0; i < detailList.size(); i++) {
      documentDetail = (DmsDocumentDetail) detailList.get(i);

      if (userDefinedDetailID.intValue() == documentDetail.getUserDefinedFieldDetailID().intValue()) {
        pos = i + 1;
        break;
      }
    }

    return pos;

  }

  /**
   *  sort the docDetail in the list base on their ID
   *
   *  @param      docDetailList             doc detail list
   *  @return     sort docDetailList        the list of docDetailList
   *  @throws     ApplicationException     Throws when operation fault
   */

  public synchronized List sortDocDetailList(List docDetailList) throws ApplicationException {

    if (docDetailList != null) {

      DmsDocumentDetail[] docDetailArray = (DmsDocumentDetail[]) docDetailList.toArray(new DmsDocumentDetail[0]);

      boolean doMore = true;
      while (doMore) {
        doMore = false;
        for (int i = 0; i < docDetailArray.length - 1; i++) {
          if (docDetailArray[i].getUserDefinedFieldDetailID().intValue() > docDetailArray[i + 1].getUserDefinedFieldDetailID().intValue()) {
            DmsDocumentDetail tmpDocDetail = docDetailArray[i];
            docDetailArray[i] = docDetailArray[i + 1];
            docDetailArray[i + 1] = tmpDocDetail;
            doMore = true;
          } //end if
        } //end for
      } //end while

      return Utility.getList(docDetailArray);
      //return ( docDetailList);
    } else {
      return docDetailList;
    }
  }

  /* boolean doMore = true;
    while (doMore) {
     doMore = false;  // assume this is last pass over array
     for (int i=0; i<x.length-1; i++) {
      if (x[i] > x[i+1]) {
      // exchange elements
      int temp = x[i];  x[i] = x[i+1];  x[i+1] = temp;
      doMore = true;  // after an exchange, must look again
      }
     }
    }
   */


  /**
   * Checks the document has relationship to other documents
   * 
   * @param docID         the id of the current document
   * @param relationType  the relation type
   * @return true if there is relationship to other document
   * @throws ApplicationException
   * 
   */
  public boolean hasRelationship(Integer docID, String relationType) throws ApplicationException {
    List relationshipList = new ArrayList();
    relationshipList = this.getMtmDocuemntRelationshipListByDocumentID(docID, relationType);
    if (!Utility.isEmpty(relationshipList)) {
      return true;
    } else {
      return false;
    }
  }
  

  /**
   *  Checks the document is hard deleted or not
   *
   *  @param      docID    dmsDocument id
   *  @return     boolean  true for the document is hard deleted, false is not yet deleted
   * 
   */
  public boolean checkDocIsHardDeleted(Integer docID) throws ApplicationException {
    boolean isDeleted = false;
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    //if the document not exist, then mean is deleted.
    isDeleted = !dmsDocumentDAO.checkDocExist(docID);
    
    return isDeleted;
  }
  
  /**
   *  Checks the root is hard deleted or not
   *
   *  @param      rootID    dmsRoot id
   *  @return     boolean   true for the root is deleted, false is not yet deleted
   * 
   */
  public boolean checkRootIsHardDeleted(Integer rootID) throws ApplicationException {
    boolean isDeleted = false;
    //DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);    
    //if the document not exist, then mean is deleted.
    isDeleted = !dmsRootDAO.checkDocExist(rootID);
    
    return isDeleted;
  }  
  
  /**
   * Gets the archive segment ID String in 3 digits
   * 
   * @param dmsArchive
   * @param documentID
   * @param versionID
   * @return segment string of the corresponding archived document.
   * @throws ApplicationException
   */
  public String getSegment(DmsArchive dmsArchive,Integer documentID,Integer versionID) throws ApplicationException{
    DmsArchiveDetailDAObject dmsArchiveDetailDAO=new DmsArchiveDetailDAObject(sessionContainer,conn); 
    DmsArchiveDetail dmsArchiveDetail=(DmsArchiveDetail)dmsArchiveDetailDAO.getSegmentByArchiveIDDocIDVersionID(dmsArchive.getID(),documentID,versionID);
    Integer segmentID=dmsArchiveDetail.getArchiveSegmentID();
    String segment="";
    if(segmentID!=null){
      if(segmentID.intValue()<10){
        segment="00"+segmentID.toString();
      }else if(segmentID.intValue()>=10 && segmentID.intValue()<100){
        segment="0"+segmentID.toString();
      }else{
        segment=segmentID.toString().toString();
      }
    }
    segment=dmsArchive.getArchiveName()+"_"+segment;
    return segment;
  }
  
  /**
   * Gets the document (not include shortcut) with the same name of the 
   * given document under the same folder 
   * 
   * @param dmsDocument
   * @return document in duplicate name
   * @throws ApplicationException
   */
  public DmsDocument getDuplicateNameDocSameLevel(DmsDocument dmsDocument)throws ApplicationException{
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    boolean checkDuplicateName = true;  //used to cater the uploaded document
    Boolean supportDuplicateName = new Boolean(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_SUPPORT_DUPLICATE_NAME));

    // check for invalid characters on document name only
    //TextUtility.stringValidation(dmsDocument.getDocumentName());
    DmsDocument existDoc = null;
    if ( supportDuplicateName.booleanValue() == false) {  
      boolean existence = false;
      DmsDocumentDAObject documentDAO = new DmsDocumentDAObject(sessionContainer, conn);
  
      List existDocList = documentDAO.getDuplicateNameInSameLevel(dmsDocument);
       if (existDocList !=null && !existDocList.isEmpty()) {
         existDoc = (DmsDocument)existDocList.get(0);
         if(((DmsDocument.DOCUMENT_LINK).equals(existDoc.getDocumentType())) &&
               (!(DmsDocument.DOCUMENT_LINK).equals(dmsDocument.getDocumentType()))){
           //existence = false;
           return null;
         }else{
           //existence = true;
           return existDoc;
         }
       }
       documentDAO=null;
    }

    return existDoc;
  }
  
  /**
   * Gets the name of the default profile field by the field ID
   * @param fieldID the default profile field ID
   * @return field name
   * @throws ApplicationException
   * @see com.dcivision.dms.bean.DmsDefaultProfileSetting
   */
  public String getDefaultProfileFieldName(Integer fieldID) throws ApplicationException{
    String rtnProfileName = "";
    DmsDefaultProfileSettingDAObject dmsDPFDAO = new DmsDefaultProfileSettingDAObject(sessionContainer,conn); 
    DmsDefaultProfileSetting defaultProfile = (DmsDefaultProfileSetting)dmsDPFDAO.getDPFByID(fieldID);
    if(defaultProfile!=null){
      rtnProfileName = defaultProfile.getFieldName();
    }
    return rtnProfileName;
  }

  /**
   *  Gets the have access setting dmsDocument list under the directory.
   *
   *  @param parentID                       The parentID of parent directory.
   *  @param rootID                         The rootID of root directory.
   *  @return                               The List of folders under that directory.
   *  @throws ApplicationException          Throws when list operation fault.
   */
  public synchronized List getAccessFolderByParentIDRootID(Integer parentID, Integer rootID,String docIDStr ) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List documentList = dmsDocumentDAO.getListByParentID(parentID, rootID, "*" , docIDStr);
    List finalList = new ArrayList();
    List tmpList = null;
    finalList.addAll(documentList);
    if (!Utility.isEmpty(documentList)) {
      for (int i = 0; i < documentList.size(); i++) {
        DmsDocument doc = (DmsDocument) documentList.get(i);
        tmpList = getAccessFolderByParentIDRootID(doc.getID(), doc.getRootID(), docIDStr);
        if (!Utility.isEmpty(tmpList)) {
          finalList.addAll(tmpList);
        }
      }
    }
    dmsDocumentDAO = null;
    return finalList;
  }

  /**
   * Gets String of the permission ID of the object divided into user, group and role
   * @param objectID
   * @return String of the permission ID 
   * @throws ApplicationException
   */
  public String selectPermissionObjects(Integer objectID) throws ApplicationException {

    String objectType = "D";
    StringBuffer allPermissionData = new StringBuffer();
    StringBuffer userNoPermissionData = new StringBuffer();
    StringBuffer groupNoPermissionData = new StringBuffer();
    StringBuffer roleNoPermissionData = new StringBuffer();

    if (objectID == null) {
      objectID = new Integer(0);
    }

    // User
    UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionContainer, conn);
//    String[][] saUserHasPerm = userRecordDAO.getHasPermissionArrayByObjectTypeObjectID(objectType, objectID);
//    String[][] saUserHasNoPerm = userRecordDAO.getHasNoPermissionArrayByObjectTypeObjectID(objectType, objectID);
    String[][] saUserHasPerm = userRecordDAO.getHasPermissionAndUpdaterArrayByObjectTypeObjectID(objectType, objectID);
    String[][] saUserHasNoPerm = userRecordDAO.getHasNoPermissionAndUpdaterArrayByObjectTypeObjectID(objectType, objectID);
    for (int i = 0; i < saUserHasPerm.length; i++) {
      for (int j = 0; j < saUserHasPerm[i].length; j++) {
        if (j == saUserHasPerm[i].length - 1) {
          allPermissionData.append(saUserHasPerm[i][j] + "\n");
        } else {
          allPermissionData.append(saUserHasPerm[i][j] + "\t");
        }
      }
    }

    for (int i = 0; i < saUserHasNoPerm.length; i++) {
      for (int j = 0; j < saUserHasNoPerm[i].length; j++) {
        if (j == saUserHasNoPerm[i].length - 1) {
          userNoPermissionData.append(saUserHasNoPerm[i][j] + "\n");
        } else {
          userNoPermissionData.append(saUserHasNoPerm[i][j] + "\t");
        }
      }
    }

    // Group
    UserGroupDAObject userGroupDAO = new UserGroupDAObject(sessionContainer, conn);
    String[][] saGroupHasPerm = userGroupDAO.getHasPermissionAndUpdaterArrayByObjectTypeObjectID(objectType, objectID);
    String[][] saGroupHasNoPerm = userGroupDAO.getHasNoPermissionAndUpdaterArrayByObjectTypeObjectID(objectType, objectID);

    for (int i = 0; i < saGroupHasPerm.length; i++) {
      for (int j = 0; j < saGroupHasPerm[i].length; j++) {
        if (j == saGroupHasPerm[i].length - 1) {
          allPermissionData.append(saGroupHasPerm[i][j] + "\n");
        } else {
          allPermissionData.append(saGroupHasPerm[i][j] + "\t");
        }
      }
    }

    for (int i = 0; i < saGroupHasNoPerm.length; i++) {
      for (int j = 0; j < saGroupHasNoPerm[i].length; j++) {
        if (j == saGroupHasNoPerm[i].length - 1) {
          groupNoPermissionData.append(saGroupHasNoPerm[i][j] + "\n");
        } else {
          groupNoPermissionData.append(saGroupHasNoPerm[i][j] + "\t");
        }
      }
    }
    // Role
    UserRoleDAObject userRoleDAO = new UserRoleDAObject(sessionContainer, conn);
    String[][] saRoleHasPerm = userRoleDAO.getHasPermissionAndUpdaterArrayByObjectTypeObjectID(objectType, objectID);
    String[][] saRoleHasNoPerm = userRoleDAO.getHasNoPermissionAndUpdaterArrayByObjectTypeObjectID(objectType, objectID);

    for (int i = 0; i < saRoleHasPerm.length; i++) {
      for (int j = 0; j < saRoleHasPerm[i].length; j++) {
        if (j == saRoleHasPerm[i].length - 1) {
          allPermissionData.append(saRoleHasPerm[i][j] + "\n");
        } else {
          allPermissionData.append(saRoleHasPerm[i][j] + "\t");
        }
      }
    }

    for (int i = 0; i < saRoleHasNoPerm.length; i++) {
      for (int j = 0; j < saRoleHasNoPerm[i].length; j++) {
        if (j == saRoleHasNoPerm[i].length - 1) {
          roleNoPermissionData.append(saRoleHasNoPerm[i][j] + "\n");
        } else {
          roleNoPermissionData.append(saRoleHasNoPerm[i][j] + "\t");
        }
      }
    }
    return allPermissionData.toString();
  }  


  /**
   *  Checks the folder or document permission is inherit form parent.
   *
   *  @param documentID                       The parentID of parent directory.
   *  @return           true if the folder or document permission is inherit form parent.
   */  
  public boolean checkFolderIsInheritParent(Integer documentID){
    boolean returnFlag = true;
    
    UserPermissionInheritDAObject userPermissionInheritDAObject = new UserPermissionInheritDAObject(sessionContainer, conn);
    try{
      UserPermissionInherit userPermissionInherit = 
        (UserPermissionInherit)userPermissionInheritDAObject.getObjectByObjectTypeObjectID(
                GlobalConstant.OBJECT_TYPE_DOCUMENT,documentID);
      if(!Utility.isEmpty(userPermissionInherit)){
        if ("N".equals(userPermissionInherit.getInheritanceFlag())){
          returnFlag = false;
        }
      }else{
        returnFlag = true;  
      }
    }catch(Exception e){
      returnFlag = false;  
    }
    return returnFlag;
  }
  
  /**
   * Gets the target document that has the relationship of the given document
   * @param docID   the given document ID
   * @param relationType  the relationType
   * @return  the target document 
   * @throws ApplicationException
   */
  public DmsDocument getRelationshipTargetDocument(Integer docID,String relationType) throws ApplicationException {
    return getRelationshipTargetDocument(docID,relationType,null);
  }
  
  /**
   * Gets the target document that has the relationship of the given document
   * @param docID            the given document ID
   * @param relationType     the relationType
   * @param recordStatus     active to get the active target document, inactive to get the inactive target document
   * @return                 the target document
   * @throws ApplicationException
   */
  public DmsDocument getRelationshipTargetDocument(Integer docID,String relationType,String recordStatus) throws ApplicationException {
   MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
   DmsDocumentDAObject dmsDocmentDAO = new DmsDocumentDAObject(sessionContainer, conn);
   Integer targetDocID = docRelationshipDAO.getTargetDocIDByRelatedDocID(docID, relationType);
   if(targetDocID==null){
     return null;
   }
   DmsDocument targetDoc = null;
   try{
     if(!Utility.isEmpty(recordStatus)){
        targetDoc=(DmsDocument)dmsDocmentDAO.getByIDRecordStatus(targetDocID,recordStatus); 
     }else{
       targetDoc=(DmsDocument)dmsDocmentDAO.getObjectByID(targetDocID);
     }
   }catch(ApplicationException aex){
     return null;
   }
    return targetDoc;
  }


  /**
 * Gets all target document (include active and inactive) of the current document that has relationship
 * @param docID
 * @param relationType
 * @return List List of the target documents
 * @throws ApplicationException
   */  
  public List getInactiveActiveRelatedDocument(Integer docID,String relationType) throws ApplicationException {
    MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    //Integer targetDocID = (Integer)docRelationshipDAO.getTargetDocIDByRelatedDocID(docID, relationType);
    List allRelatedDocList = new ArrayList();
    List relatedDocIDList = docRelationshipDAO.getRelatedDocIDByDocID(docID,DmsDocument.DOCUMENT_LINK,GlobalConstant.RECORD_STATUS_ACTIVE);
    List inActiveRelatedDocIDList =  docRelationshipDAO.getRelatedDocIDByDocID(docID,DmsDocument.DOCUMENT_LINK,GlobalConstant.RECORD_STATUS_INACTIVE);
    List allRelatedDocIDList = new ArrayList();
    allRelatedDocIDList.addAll(relatedDocIDList);
    allRelatedDocIDList.addAll(inActiveRelatedDocIDList);
    
    if(Utility.isEmpty(allRelatedDocIDList)){
      return null;
    }else{
      for(int i=0; i<allRelatedDocIDList.size();i++){
        Integer tmpDocID = (Integer)allRelatedDocIDList.get(i);
        DmsDocument tmpDocument = (DmsDocument)dmsDocumentDAO.getActiveInactiveByID(tmpDocID);
        allRelatedDocList.add(tmpDocument);
      }
    }
    
    return allRelatedDocList;
    
   
   }
  
  /**
   * Gets dmsRoot by the document ID.
   * 
   * @param documentID
   * @return DmsRoot
   * @throws ApplicationException
   * @see com.dcivision.dms.bean.DmsRoot
   */
  public DmsRoot getDmsRoot(Integer documentID) throws ApplicationException {
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);
    DmsRoot dmsRoot = (DmsRoot) dmsRootDAO.getObjectByID(documentID);
    dmsRootDAO = null;
    return dmsRoot;

  }
  
  /**
   * Gets the personal Root by owner ID and record status
   * @param ownerID
   * @param recordStatus
   * @return Personal root
   * @throws ApplicationException
   */
  public DmsRoot getDmsRootID(Integer ownerID, String recordStatus) throws ApplicationException{
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);
    DmsRoot dmsRoot = dmsRootDAO.getPersonalRootByOwnerIDAndType(ownerID,recordStatus);
    dmsRootDAO = null;
    return dmsRoot;
  }

  /**
   * gets list of documents which is ancestor of the current document.
   *
   * @param CurrentDocumentID
   * @return List list of documents
   * @throws ApplicationException
   */
  public synchronized List getAllParentDocumentList(Integer CurrentDocumentID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);

    List parentDocumentList = new ArrayList();
    List tempParentDocumentList = null;
    if (CurrentDocumentID.intValue() != 0) {
      DmsDocument doc = (DmsDocument) dmsDocumentDAO.getObjectByID(CurrentDocumentID);
      if (doc != null) {        
        parentDocumentList.add(doc);
        tempParentDocumentList = getAllParentDocumentList(doc.getParentID());
        if (!Utility.isEmpty(tempParentDocumentList)) {
          parentDocumentList.addAll(tempParentDocumentList);
        }
      }
    }
    
    dmsDocumentDAO = null;
    return parentDocumentList;
  }  
  /**
 * Gets Home folder of specified user, group or role
    *
 * @param objectType  Object type (DmsObjectHomeFolder.MEMEBER_TYPE_USER,MEMBER_TYPE_GROUP
 *                                 DmsObjectHomeFolder.MEMBER_TYPE_ROLE)
 * @param objectID    Object ID
 * @return  Home folder
 * @throws ApplicationException
 * @see com.dcivision.dms.bean.DmsObjectHomeFolder
    */
  public DmsDocument getHomeFolderByObjectTypeAndID ( String objectType, Integer objectID ) throws ApplicationException {
    DmsObjectHomeFolderDAObject dmsObjectHomeFolderDAO=new DmsObjectHomeFolderDAObject(sessionContainer,conn);
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer,conn);
    Integer documentID = null;
    DmsDocument dmsDocument = new DmsDocument();
    
    if(DmsObjectHomeFolder.MEMEBER_TYPE_USER.equals(objectType)){
      DmsRoot dmsRoot = dmsRootDAO.getPersonalRootByOwnerIDAndType(objectID,GlobalConstant.RECORD_STATUS_ACTIVE);
      if (dmsRoot.getID() != null){
        dmsDocument = this.getRootFolderByRootID(dmsRoot.getID());
      }
    }else if((DmsObjectHomeFolder.MEMBER_TYPE_GROUP.equals(objectType))||
             (DmsObjectHomeFolder.MEMBER_TYPE_ROLE.equals(objectType)) ){
     
      documentID = dmsObjectHomeFolderDAO.getDocIDByMemberIDType(objectType,objectID);
      if(documentID!=null){
        dmsDocument = this.getDocument(documentID);
      }         
    }
    
    dmsObjectHomeFolderDAO = null;
    if(dmsDocument.getID()!=null){
      return dmsDocument;
    }else{
      return null;
    }
    
  }
  /**
   * Gets a zip file which contains the compound document and its supporting document(s)
   *
   * @param document Compound document
   * @param request
   * @param response
   * @return  zip file path
   * @throws ApplicationException
   */
  public StringBuffer getCompoundZip(DmsDocument document,HttpServletRequest request,HttpServletResponse response) throws ApplicationException{
    return getCompoundZip(document);
  }

  /**
   * @param document
   * @return
   * @throws ApplicationException
   */
  public StringBuffer getCompoundZip(DmsDocument document) throws ApplicationException {
    //SessionContainer sessionContainer=this.getSessionContainer(request);
    //Connection conn=this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    InputStream inputStream = null;
    InputStream dataStream = null;
    String zipfilename = document.getDocumentName() + ".zip";
    StringBuffer comZipFile = new StringBuffer();
    DmsLocMaster locMaster = rootRetrievalManager.getTargetLocMasterByDocument(document);
    String locMasterPath = locMaster.getLocPath();
    comZipFile = comZipFile.append(locMasterPath).append("/").append(zipfilename);
    DmsContentManager dmsContentManager = new DmsContentManager(sessionContainer, conn);

    try {
//      FileOutputStream fileOutputStream = new FileOutputStream(comZipFile.toString());
//      CheckedOutputStream cosm = new CheckedOutputStream(fileOutputStream, new Adler32());
//      ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(cosm));
      ZipOutputStream zos= new ZipOutputStream(new FileOutputStream(comZipFile.toString()));      
      DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
      MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
      //List list=new ArrayList();
      Integer targetID = document.getID();
      Integer contentID = null;
      DmsVersion dmsVersion = new DmsVersion();
      MtmDocumentRelationshipDAObject docReBufferedInputStreamlationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
      List list = docOperationManager.getSubDocumentByParentID(document.getID());
      if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType()) ||
         DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType()) ||
         DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType()) ||
         DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType())){
        list.add(document);
      }
      //Object[] putStream=new Object[list.size()];
      if (!Utility.isEmpty(list)) {
        for (int j = 0; j < list.size(); j++) {
          DmsDocument dmsDocument = (DmsDocument) list.get(j);
          String fName = DocumentRetrievalManager.getEncodeStringByEncodeCode(dmsDocument.getDocumentName()
              ,SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_ZIP_FILE_DEFAULT_ENCODING));
          DmsVersion sVersion = docRetrievalManager.getTopVersionByDocumentID(dmsDocument.getID());
          contentID = sVersion.getContentID();
          if (DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())) {
            Integer targetDocID = docRelationshipDAO.getTargetDocIDByRelatedDocID(dmsDocument.getID(), dmsDocument.getDocumentType());
            DmsDocument targetDoc = docRetrievalManager.getDocument(targetDocID);
            /* Used to update the doc link name and type; Wont infulence the getDocumentProfileInfo() */
            if (targetDoc != null) {
              targetDoc.setDocumentName(dmsDocument.getDocumentName());
              targetDoc.setDocumentType(dmsDocument.getDocumentType());
              //update the doc ID for shortcut linkage
              targetID = targetDocID;
              dmsDocument = targetDoc;
              if(!DmsDocument.DOCUMENT_TYPE.equals(dmsDocument.getDocumentType()) ){
                continue;
              }             
              
              //update the real link document version
              sVersion = docRetrievalManager.getTopVersionByDocumentID(targetID);
              contentID = sVersion.getContentID();
            } else {
              document.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
            }
          }
          if (!GlobalConstant.RECORD_STATUS_INACTIVE.equals(document.getRecordStatus())) {
            DmsContent docContent = docRetrievalManager.getContentByContentID(contentID);
            dataStream = dmsContentManager.readDmsDocumentStoreContent(dmsDocument,docContent);

            //putStream[j]=dataStream;
            ZipEntry theEntry = new ZipEntry(dmsDocument.getDocumentName());//fName);//Update By Jim.Zhou	2006/08/11	Bug	#5979
            zos.putNextEntry(theEntry);

            byte[] buffer = new byte[8192];
            int length = -1;
            inputStream = dataStream;
            while ( (length = inputStream.read(buffer, 0, 8192)) != -1) {
              zos.write(buffer, 0, length);
            }
          }
        }
        //inputStream=putStream.
      }
      zos.flush();
      zos.close();
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(com.dcivision.framework.ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
      try {
        inputStream.close();
      } catch (IOException ignore) {
        inputStream = null;
      }
    }
    return comZipFile;
  }
  /**
 * Checks whether the document has subDocuments
 * @param dmsDocument
 * @param request
 * @return true if the given documents has subdocument(s)
 * @throws ApplicationException
   */
  public boolean hasSubDocument(DmsDocument dmsDocument,HttpServletRequest request) throws ApplicationException{
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);  
    List list= docOperationManager.getSubDocumentByParentID(dmsDocument.getID()); 
    if(list.size()>0){
      return true;   
    }else{
      return false;   
    }
  }
  
  /**
     * get a document by document type and Reference no.
     *
     * @documentType   the type of the document
     * @referenceNo    the reference no of the document
     * @return  DmsDocument  
     */
   public DmsDocument getDocumentByDocTypeRefNo( String documentType, String referenceNo ) throws ApplicationException {
     
     DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
     DmsDocument dmsDocument = dmsDocumentDAO.getDocumentByDocTypeRefNo(documentType,referenceNo);
     dmsDocumentDAO = null;
     return dmsDocument;
    
   }
   
   /**
    * get dms root by document id.
    * @param documentID
    * @return DmsRoot
    * @throws ApplicationException
    */
   public DmsRoot getDmsRootByDocumentID(Integer documentID) throws ApplicationException {
     DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);
     DmsDocument dmsDocument=this.getDocument(documentID);
     DmsRoot dmsRoot = (DmsRoot) dmsRootDAO.getObjectByID(dmsDocument.getRootID());
     return dmsRoot;
  }
   
    /**
     * Checks the default user defined field has value or not
     * @param numOfFields  default user defined field position
     * @return true if the default user defined field has value
     * @throws ApplicationException
     */
   public  boolean hasUserDEF(int numOfFields) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List uDFList = dmsDocumentDAO.getAllDocumentUDFList();
    boolean hasUserDF=false;
    try{
      if(uDFList.size()>0){
        for(int i=0;i<uDFList.size();i++){
          DmsDocument dmsDocument = (DmsDocument)uDFList.get(i);
          String[] userDef=new String[numOfFields];
          for(int d=0;d<userDef.length;d++){
            Method getFileMth = dmsDocument.getClass().getMethod("getUserDef"+numOfFields,null); 
            userDef[d]=(String)getFileMth.invoke(dmsDocument, null);
            if(!Utility.isEmpty(userDef[d])){
              hasUserDF=true;
            }else{
              hasUserDF=false;
            }
          }
        }
     }
    dmsDocumentDAO=null;
   }catch(Exception e){
     log.error(e, e);
   }
   return hasUserDF;
   }
   
  /***
   * Gets the personal Root ID of current user
   * 
   * @return
   * @throws ApplicationException
   */
   public Integer getRootID() throws ApplicationException{
     Integer rootID = null;
     DmsRoot dmsRoot = null;
     Integer userID = sessionContainer.getUserRecordID();
     DmsRootDAObject rootDAO = new DmsRootDAObject(this.sessionContainer, conn);
     List rootList = rootDAO.getRootByOwnerIDAndType(userID, DmsRoot.PERSONAL_ROOT,GlobalConstant.RECORD_STATUS_ACTIVE);
     if(!Utility.isEmpty(rootList)){
       dmsRoot = (DmsRoot)rootList.get(0);
       rootID = dmsRoot.getID();
     } 
     
     return rootID;
   }


   /**
    * get a document closest parent folder that this parent folder have default profile  
    * @param documentID
    * @return Document
    * @throws ApplicationException
    */   
   public DmsDocument getClosestHaveDefaultProfileFolder(Integer documentID)throws ApplicationException{
     List folderList = getAllParentDocumentList(documentID);
     DmsDocument folder = null;

     if( !Utility.isEmpty(folderList)){
        for(int i=0;i < folderList.size();i++){
            DmsDocument tmpFolder =  (DmsDocument)folderList.get(i);    
            
            // if this folder hava default profile ,retun this folder
            if(!Utility.isEmpty( tmpFolder.getUserDef1())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef2())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef3())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef4())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef5())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef6())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef7())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef8())){
                folder = tmpFolder;
                break;
            }
            if(!Utility.isEmpty( tmpFolder.getUserDef9())){
                folder = tmpFolder;
                break;
            }            
            if(!Utility.isEmpty( tmpFolder.getUserDef10())){
                folder = tmpFolder;
                break;
            }            
            List docDetailList = getDocumentDetailList(documentID);
            // if this folder hava profile value,retun this folder            
            if( !Utility.isEmpty(docDetailList)){
                folder = tmpFolder;
                break;                
            }
        }
     }
     return folder;
   }
   
   
   public DmsDocument getMyFavoriteObject() throws ApplicationException{
    DmsDocument docDocument = new DmsDocument();
    String myFavoriteName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MYFAVORITE_FOLDER_NAME);    
    //MaintMtmDocumentRelationshipForm maintDocRelationshipForm = (MaintMtmDocumentRelationshipForm)form;
    
    boolean hasMyFavorite = false;
    
    DmsRootDAObject rootDAO = new DmsRootDAObject(sessionContainer, conn);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    
    try {
      RootOperationManager rootOperationManager = new RootOperationManager(sessionContainer, conn);
      MtmDocumentRelationship docRelationship = new MtmDocumentRelationship();
      
      Integer rootID = null;
      Integer parentID = null;
      DmsDocument dmsDocument = null;   
      
       //achieve current user's persoanl object
      Integer userID = sessionContainer.getUserRecordID();      
      List rootList = rootDAO.getRootByOwnerIDAndType(userID, DmsRoot.PERSONAL_ROOT, GlobalConstant.RECORD_STATUS_ACTIVE);
      DmsRoot dmsRoot =  (DmsRoot)rootList.get(0);
      DmsDocument documentRoot = this.getRootFolderByRootID(dmsRoot.getID());
      rootID = documentRoot.getRootID();
      parentID = documentRoot.getID();      
      
      //check current personal's folder have myFavorite folder or not 
      List docList = dmsDocumentDAO.getListByParentID(parentID, rootID, DmsDocument.FOLDER_TYPE);
      for (int i=0 ;i<docList.size(); i++){
        dmsDocument = (DmsDocument)docList.get(i);
        if(myFavoriteName.trim().equals(dmsDocument.getDocumentName().trim())){
          rootID= dmsDocument.getRootID();
          parentID = dmsDocument.getID();
          hasMyFavorite = true;
          break;
        }
      } 
      
      if(!hasMyFavorite){
        DmsDocument docTemp = this.createMyFavoriteFolder(documentRoot);
        //Add By Jim Zhou   2006/10/25    EIP-777
        /*
        if (!sessionContainer.getPermissionManager().containsPermissionKey(DmsDocument.DOCUMENT_TYPE + "" + docTemp.getID().toString())) {
          sessionContainer.getPermissionManager().putPermissionIntoCache(DmsDocument.DOCUMENT_TYPE + "" + docTemp.getID().toString(), "PERSONAL");
        }
        */
        //Add End
        docDocument = docTemp;
      }else{
        docDocument = dmsDocument;
      }
      conn.commit();
      rootDAO = null;
      dmsDocumentDAO = null;
      return docDocument;
    }catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }    
  }
  
  public DmsDocument createMyFavoriteFolder(DmsDocument documentRoot) throws ApplicationException{
    
    String myFavoriteName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MYFAVORITE_FOLDER_NAME);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DmsDocument docDocument = new DmsDocument();
    
    docDocument.setDocumentName(myFavoriteName);
    docDocument.setDocumentType(DmsDocument.FOLDER_TYPE);
    docDocument.setParentID(documentRoot.getID());
    docDocument.setRootID(documentRoot.getRootID());
    docDocument.setPriority(GlobalConstant.PRIORITY_MEDIUM);
    docDocument.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);
    docDocument.setEffectiveStartDate(Utility.getCurrentTimestamp());
    docDocument.setItemSize(new Integer(0));
    docDocument.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
    docDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);  
        
    docDocument = docOperationManager.createFolder(docDocument);
    return docDocument;
  }
  
  /**
   *  Gets the dmsDocument list under the directory.
   *
   *  @param parentID                       The parentID of parent directory.
   *  @param rootID                         The rootID of root directory.
   *  @return                               The List of (DmsDocument)folders include short folder under that directory.
   *  @throws ApplicationException          Throws when list operation fault.
   */
  public synchronized List getFolderIncShorcutByParentIDRootID(Integer parentID, Integer rootID) throws ApplicationException {
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    //List documentList = dmsDocumentDAO.getListByParentIDRecordStatus(parentID, rootID, DmsDocument.FOLDER_TYPE,GlobalConstant.RECORD_STATUS_ACTIVE);
    List documentList = this.getDocumentListByParentIDRootID(parentID,rootID);
    List finalList = new ArrayList();
    for (int i=0; i<documentList.size(); i++){
      DmsDocument document = (DmsDocument)documentList.get(i);
      if((!DmsDocument.DOCUMENT_TYPE.equals(document.getDocumentType()))&& (!"P".equals(document.getRecordStatus()))){
        if(!DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
          finalList.add(document);
        }else{
          DmsDocument  newDocument = this.getRelationshipTargetDocument(document.getID(),DmsDocument.DOCUMENT_LINK );
          if(!Utility.isEmpty(newDocument)){
            if (DmsDocument.FOLDER_TYPE.equals(newDocument.getDocumentType())){
              finalList.add(document);
            }
          }
        }
      }
    }    
    
    return finalList;
  }
  
  /*
   * Update Code Start
   * Author			Jim.Zhou
   * Date			2006/04/12
   * Bug			#4820
   */
  public String getZipFileDefaultEncode(){
	  /*
	  String zipFileDefaultEncodeCode = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_ZIP_FILE_DEFAULT_ENCODING).trim().toUpperCase();
	  if ("UTF-8".equals(zipFileDefaultEncodeCode)|| "GB2312".equals(zipFileDefaultEncodeCode) || "GBK".equals(zipFileDefaultEncodeCode)){
		  return zipFileDefaultEncodeCode;
	  } else {
		  return null;
	  }
	  */
	  String zipFileDefaultEncodeCode = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_ZIP_FILE_DEFAULT_ENCODING).trim().toUpperCase();
	  if (Utility.isEmpty(zipFileDefaultEncodeCode)){
		  return null;
	  } else {
		  return zipFileDefaultEncodeCode;
	  }
  }
  /*
   * Update Code End
   */

  /**
   * getURLEncodeInUTF8
   *
   * @return  The the string encoded in UTF format
   */
  public static String getEncodeStringByEncodeCode(String str,String encodeCode) {
    String defaultEncodeCode = "UTF-8";
    String encodedStr = new String();
    
    if (str == null){
      return null;
    }
        
    //if the encodeCode is null ,then use the UTF-8 encode
    if (Utility.isEmpty(encodeCode)) {
      encodeCode = "UTF-8";
    }   
    
    try {
      encodedStr = new String (str.getBytes(defaultEncodeCode),encodeCode);
    } catch (UnsupportedEncodingException uee) {
      
    }
    return encodedStr;
  }  

  
  /**
   * use for paraScan ,check if need update profile index
   * 
   * 
   * @return the all profile the max update date
   */
  public Timestamp getAllProfileTheMaxUpdateDate(){    
    Timestamp maxUpdateDate = null;
    Timestamp sysUserDefinedIndexUpdateDate = null;
    Timestamp sysUserDefinedIndexDetailIndexUpdateDate = null;    
    Timestamp UserDefinedIndexDetailUpdateDate = null;
    Timestamp sysParameterUpdateDate = null;
    
    DmsDefaultProfileSettingDAObject udfSetDAO = new DmsDefaultProfileSettingDAObject(sessionContainer, conn);
    try{
      //get the sysUserDefindIndex update date
      sysUserDefinedIndexUpdateDate = udfSetDAO.getMaxUpdateDate("SYS_USER_DEFINED_INDEX",null);
      //get the sysUserDefindDetailIndex update date
      sysUserDefinedIndexDetailIndexUpdateDate = udfSetDAO.getMaxUpdateDate("SYS_USER_DEFINED_INDEX_DETAIL",null);
      //get the defaultProfile update date      
      UserDefinedIndexDetailUpdateDate = udfSetDAO.getMaxUpdateDate("DMS_DEFAULT_PROFILE_SETTING",null);
      //get the system parameter 6021 'dms.default_profile_field_count' 's update date     
      sysParameterUpdateDate = udfSetDAO.getMaxUpdateDate("SYS_PARAMETER",new Integer(6021));
      
      if(sysUserDefinedIndexDetailIndexUpdateDate!=null && sysUserDefinedIndexUpdateDate != null && UserDefinedIndexDetailUpdateDate!= null && sysParameterUpdateDate!=null){
        if(sysUserDefinedIndexUpdateDate.getTime() > UserDefinedIndexDetailUpdateDate.getTime()){
          maxUpdateDate = sysUserDefinedIndexUpdateDate;          
        }else{
          maxUpdateDate = UserDefinedIndexDetailUpdateDate;
        }       
        if(sysUserDefinedIndexDetailIndexUpdateDate.getTime() > maxUpdateDate.getTime()){
          maxUpdateDate = sysUserDefinedIndexDetailIndexUpdateDate;          
        }                
        if(sysParameterUpdateDate.getTime() > maxUpdateDate.getTime()){
          maxUpdateDate = sysParameterUpdateDate;          
        }        
      }
    }catch(Exception e){      
      log.error(e, e);
    }   
    
    return maxUpdateDate;
  }
  
  /* Jicle.Wang 5816 2006/08/10 Start */
  public String getPostfixByDocument(DmsDocument document){
  	Integer id = null;
  	String postfix = ""; 
  	if(!Utility.isEmpty(document) && !Utility.isEmpty(document.getID())){
  		id = document.getID();
  	}
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    postfix = dmsDocumentDAO.getPostfixByID(id);
    dmsDocumentDAO = null;
    return postfix;
  }
  /* Jicle.Wang 5816 2006/08/10 End   */
  /* Jicle.Wang 6029 2006/08/18 Start */
  /**
   * Get the postfix which relation the document.
   *  
   * @param DmsDocument  the document
   * @return If ture Return postfix which relation whith Document,else return The Document's postfix from its name.
   * @throws -
   */
  public String getPostfixByRelationDocumentId(DmsDocument dmsDocument){
	  String postfix = "";
	  MtmDocumentRelationshipDAObject mtmRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
	  DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
	  try {
		List listDocumentId = mtmRelationshipDAO.getDocIDByRelatedDocID(dmsDocument.getID(), dmsDocument.getDocumentType(), GlobalConstant.RECORD_STATUS_ACTIVE);
	    Integer id = dmsDocument.getID();
		if(listDocumentId.size()>0){
		  id = (Integer)listDocumentId.get(listDocumentId.size()-1);	      
	    }
		DmsDocument document = (DmsDocument)dmsDocumentDAO.getDocumentByID(id, GlobalConstant.RECORD_STATUS_ACTIVE);
		String documentName = document.getDocumentName();
		if(!Utility.isEmpty(documentName) && documentName.indexOf('.')>0){
		  postfix = TextUtility.getExtension(documentName);
		}
	  } catch (ApplicationException e) {
      log.error(e, e);
	}
  
	  return postfix;
  }
  /* Jicle.Wang 6029 2006/08/18 End   */
  
  /**
   * this method according to objectIds get its all sub documents 
   * @author barbin
   * @create 2007-02-08
   * @return objectIDs
   */
  public List getAllsubFolderDocIDsByObjectID(List objectIDs,Integer rootID){
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    try{
      // clcye get document ids
      for(int i = 0 ;i<objectIDs.size();i++){
        List tempList = new ArrayList();
        tempList = dmsDocumentDAO.getAllsubFolderDocIDsByObjectID((Integer)objectIDs.get(i),rootID);
        if (tempList.size()>0){
          objectIDs.addAll(tempList);
          this.getAllsubFolderDocIDsByObjectID(tempList,rootID);
        }
      }      
    }catch(Exception e){
      log.error(e, e);
    }
    return objectIDs;
  }
  public List getRelationshipList(Integer documentID){
    MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
    List relationDocumentList = null;
    try{
      relationDocumentList = dmsMtmDocumentRelationshipDAO.getListByIDRelationType(documentID,"");
   } catch (Exception ee) {
     log.error(ee, ee);
   }
    return relationDocumentList;
  }
  
  public List getIndirectRelationshipList(Integer documentID){
    MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
    List IndirectRelationDocumentList = null;
    try{
      IndirectRelationDocumentList = dmsMtmDocumentRelationshipDAO.getListByRelationIDRelationType(documentID,"");
    } catch (Exception ee) {
      log.error(ee, ee);
    }
    return IndirectRelationDocumentList;
  }
  
}
  
